Async + ExpectedException

Mar 18, 2014 at 10:02 AM
Hello!

Firstly: Thanks for the great project and continued support. You're saving our project :)

I have one question though: I'd like to test exceptions on my ViewModels in Silverlight 5. I use the Async CTP, so the exception will occur in another Thread. This crashes the runner and sometimes even freezes up VS2013.

Is there a way to prevent this? I already tried to decorate my Test with [Asynchronous], but that won't help. Here's my code:
[TestMethod, ExpectedException(typeof(ArgumentNullException))]
public void RemoveAssociationCommand_ExecutedWithNull_Throws()
{
    // Arrange
    var fixture = new Fixture();
    var sut = fixture.CreateSut();

    // Act
    sut.RemoveAssociationCommand.Execute(null);  // MvvmLight EventToCommand

    // Assert
}
The method behind RemoveAssociationCommand is async, and this is where the expected exception gets thrown:
private async void Remove(ITextAutocomplete item)
{
    if (item == null)
        throw new ArgumentNullException("item");
        
    // ...
}
The methods needs to be async, because in the standard case, various asynchronous services get called. The error I get is the following:

Image

Is there a workaround for this?

Thanks in advance!

Luetm
Coordinator
Mar 18, 2014 at 10:10 AM
Hi,

Can you try awaiting the Execute method?

AgUnit (StatLight actually) has no support for async. Your test needs to complete synchronously (or see below) so you'll need to await your calls to async methods.

The [Asynchronous] attribute is for UI (Dispatcher) unit testing:
http://www.jeff.wilcox.name/2009/03/asynchronous-testing/

Steven
Mar 18, 2014 at 10:13 AM
Hi Steven

Thanks for the quick reply!

Unfortunately, the RelayCommand.Execute Method returns void, so I cannot await it.

Is there a possibility to implement this? I'd be glad to help, if you direct me to the right sections a little :-)

Luetm
Coordinator
Mar 18, 2014 at 10:20 AM
In your situation, this would not help.

You need to have a way for the unit test (runner) to know your async calls have completed (or throw an exception).
And you can only do that by having the Execute method be async (return a Task).

The only thing that we could implement in AgUnit/StatLight is having your test itself async. But that would not help your case.

I suggest looking into the EventToCommand code to see if you can make that async.
Mar 18, 2014 at 10:47 AM
I made the creator of MvvmLight aware of the issue. Let's hope, he has something :/