In .NET 4.5 Microsoft introduced Async methods, which helps developers write asynchronous code similar to normal code. Instead of returning ActionResult async method returns Task
This post is about various methods which helps to write unit tests. XUnit is used as unit framework. Here is the async controller code.
_employeeRepository is the repository class, which is injected via constructor using ASP.NET dependency injection framework.
Approach #1: Using Task.Wait and Task.Result - Here is the first approach, where you can wait for task, once it finished, you can verify the result, like this.
But one problem with this approach is exception scenarios; Async methods wrap specific exception using AggregateException. So it is difficult to compare between expected exception and aggregate exception. In XUnit, this won’t create problem, since XUnit supports Assert.ThrowsAsync() syntax, unlike ExpectedException attribute in the test method.
Approach #2: Using Async Test Methods - Here is the second approach, similar to source code, need to modify test code also Async. Here is the implementation.
Most of the modern unit testing frameworks support Async methods. You can find the source code in GitHub
What do you think? I would like to hear your thoughts, suggestions, and questions in the comments section below.
Did you like this article? Share it with your friends