Async + ExpectedException

Mar 18, 2014 at 9:02 AM

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:


Is there a workaround for this?

Thanks in advance!

Mar 18, 2014 at 9:10 AM

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:

Mar 18, 2014 at 9: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 :-)

Mar 18, 2014 at 9: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 9:47 AM
I made the creator of MvvmLight aware of the issue. Let's hope, he has something :/