Saturday 17 November 2012

Unit Testing Asynchronous methods using MSTest and XUnit

As we saw in previous posts, writing asynchronous code has become quite easy with .NET framework 4.5. To be able to write well and bug less code in any framework or language, unit tests play a vital role. Unit testing asynchronous code is a bit tricky and it is currently not supported by all unit test frameworks. In this post, we will see how to unit test an asynchronous method using MSTest and the XUnit framework.

Irrespective of the unit testing framework used, the test method written to test the asynchronous method has to follow a set of rules.
  • Test method should be marked as async
  • await keyword should be used while calling the method to be tested
  • Return type of the test method should be Task

I will be using the following asynchronous method for unit testing. It is a very simple method (I have used it in my post on Asynchronizing a C# method using async and await), that divides two numbers with a delay of 2 seconds.
public class ArithemticOperations
{
    public async Task<double> DivideAsync(int first, int second)
    {
        await Task.Delay(2000);
        return (double)second / first;
    }
} 

Unit testing using MSTest

MSTest is the testing framework built into Visual studio. If you are familiar with it, then testing asynchronous method doesn’t require much learning. If you are not already familiar with MSTest, you may go through Unit Testing Framework portion on MSDN.

Testing an asynchronous method is much similar to testing a synchronous method. We just need to follow the rules mentioned above. Following is a test class that tests the divide method created above.
[TestClass]
public class AsyncMethodUnitTests
{
    [TestMethod]
    public async Task DivideAsync_Returns_RightResult()
    {
        int first = 10, second = 20;
        double expected = 2.0;
        ArithemticOperations operations = new ArithemticOperations();
        double actual = await operations.DivideAsync(first, second);
        Assert.AreEqual(actual, expected);
    }
}


Unit testing using XUnit

XUnit is created by James Newkirk and Brad Wilson. It is built to support Test Driven Development with a design goal of simplicity. You may visit the Codeplex site of XUnit to learn more about it.

Testing asynchronous code using XUnit is very straight forward. Following is a test class that tests the divide method:
public class AsyncTests
{
    [Fact]
    public async Task AsyncDivide_Returns_RightResult()
    {
        int first = 10, second = 20;
        double expected = 2;
        ArithemticOperations operations = new ArithemticOperations();
        double actual = await operations.DivideAsync(first, second);
        Assert.Equal(actual, expected);
    }
}

Along with making your code run better by applying asynchronous strategies, you can unit test and even test drive them.

Happy coding!

1 comment:

Note: only a member of this blog may post a comment.