Unit Testing async MVC Controller methods

14 03 2014

Just had a strange encounter in VS 2013 unit testing. I wrote a unit test for the ASP.NET Identity AccountController, which has some asynchronous methods.
My good old friend Resharper told me to change the method signature to public async void, as I wrote the code to call my controller method using await. The code looked like this:

[TestClass] public class AccountControllerTest {     [TestMethod]
     public async void Register()
     {…
var result = await controller.Register(userModel);

}

}

 

If you run this, it builds well, but nothing happens, even debugging the test is not working. The test is invisible to the test runner!

Strange thing, which, thank good, is not happening too often in Visual Studio.

The only message I got, after fiddling around, was that there are no tests found in my class file.

Even stranger, as my test attributes proof sufficiently, I did all things required to make my test detectable to unit testing, so why is it not carried out???

Did it turn into a phantom? Black magic going on?

No, do not worry, it is not so exciting. As I had to discover, it is the async void keywords!

The background for this is reasonable, because “async void” methods are “fire and forget” ones, which may never come back and this does not really make sense in a test environment, where you need to collect results and assertions from a method. 

What is the correct way to test an aysnc method, then?

You have to use task as return type instead of void, this works well!

[TestClass] public class AccountControllerTest {     [TestMethod]
     public async Task Register()
     {…
var result = await controller.Register(userModel);

}

}

 

Alexander


Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: