Is there a way to unit test an async method?

Jiho Han picture Jiho Han · Jul 23, 2009 · Viewed 11.3k times · Source

I am using Xunit and NMock on .NET platform. I am testing a presentation model where a method is asynchronous. The method creates an async task and executes it so the method returns immediately and the state I need to check aren't ready yet.

I can set a flag upon finish without modifying the SUT but that would mean I would have to keep checking the flag in a while loop for example, with perhaps timeout.

What are my options?

Answer

justin.m.chase picture justin.m.chase · May 10, 2012

Just thought you might want an update on this since the #1 answer is actually recommending an older pattern to solve this problem.

In .net 4.5 + xUnit 1.9 or higher you can simply return a Task and optionally use the async keyword from your test to have xunit wait for the test to complete asynchronously.

See this article on xUnit.net 1.9

[Fact]
public async Task MyAsyncUnitTest()
{    
  // ... setup code here ...     
  var result = await CallMyAsyncApi(...);     
  // ... assertions here ...
}