Search code examples
.netunit-testingxunit.netnmock

Is there a way to unit test an async method?


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?


Solution

  • Does your object feature any sort of signal that the asynchronous method is finished, such as an event? If that is the case, you can use the following approach:

    [Test]
    public void CanTestAsync()
    {
        MyObject instance = new MyObject()
        AutoResetEvent waitHandle = new AutoResetEvent(false); 
        // create and attach event handler for the "Finished" event
        EventHandler eventHandler = delegate(object sender, EventArgs e) 
        {
            waitHandle.Set();  // signal that the finished event was raised
        } 
        instance.AsyncMethodFinished += eventHandler;
    
        // call the async method
        instance.CallAsyncMethod();
    
        // Wait until the event handler is invoked
        if (!waitHandle.WaitOne(5000, false))  
        {  
            Assert.Fail("Test timed out.");  
        }  
        instance.AsyncMethodFinished -= eventHandler;    
        Assert.AreEqual("expected", instance.ValueToCheck);
    }