yefajouri
yefajouri

Reputation: 86

Unit Testing async void MVC Controller methods don't run

I was trying to test userController to get users async by its service, doing the test method void. The thing is that everything compiles but then the test dont run.

[TestClass]
public class UserControllerTests
{
   [TestMethod]
   public async void UserController_GetAll_Returns_Not_Null()
   {
    var result = await controller.GetALL();

    Assert.IsNotNull(result);
   }
}

Upvotes: 1

Views: 192

Answers (2)

Stephen Cleary
Stephen Cleary

Reputation: 456977

If you look carefully at your output window, under "test detection" (or whatever it's called), you'll see that MSTest is giving you warning UTA007.

In contrast, xUnit supports them by default, while Fixie detects them and fails them explicitly.

The best solution, as you discovered, is to change the abnormal async void to the much more natural async Task. async Task works with all modern unit test frameworks.

I have more details on asynchronous unit testing in my slides from a talk on that subject I gave at ThatConference this year.

Upvotes: 0

yefajouri
yefajouri

Reputation: 86

I found the answer in "Alexander's Embedded Techwire" here link just changing async void for async task.

“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.

    [TestClass]
    public class UserControllerTests
    {
       [TestMethod]
       public async Task UserController_GetAll_Returns_Not_Null()
       {
          var result = await controller.GetALL();

          Assert.IsNotNull(result);
       }
   }

Upvotes: 2

Related Questions