1

I've a method in my controller with this signature

public async Task<ViewResult> Index()

This is what I'm doing in my unit test to wait for the result of Index()

[TestMethod]
public void TestIndex()
{
   var controller = new MyController();
   var result = controller.Index().Result;

   // Asserts here
}

But the documentation say that the way to test async methods is using async Task in the signature of the test method and using await like this

public async Task TestIndex()
{
   var controller = new MyController();
   var result = await controller.Index();

   // Asserts here
}

I really want to know what is the difference between the way the documentation say and the way I'm doing it?

What's wrong doing the test the way I'm doing it?

PS: Even the exceptions thrown in the Index method are shown in the Test Explorer window.

vcRobe
  • 1,671
  • 3
  • 17
  • 35
  • 3
    Is there a reason you're not doing it the way the documentation says to? When you're using `async` methods your code should be `async` "top-down" and calling `.Result` in a blocking manner must be avoided. – Dai Sep 14 '17 at 16:27
  • When async method is void your test must be avoided as you cant wait till the result. I'm not sure why you can't do this here though. https://msdn.microsoft.com/en-us/magazine/dn818493.aspx discusses unit testing async. – Yair Halberstadt Sep 14 '17 at 16:30

0 Answers0