Have you ever tried unit testing a method marked with async? There’s a known problem of unit testing the Async marked methods. When Nunit tried to run the test with mocked Async methods it goes in Infinite wait. There are many discussion on the internet for the same giving you the solutions and work around. This post will provide you with another solution.
Let’s start and setup a test project to reproduce the problem. So first we need library that contains the methods marked with Async keyword.
First we need the marker interface:
Now lets write a unit test to test this method for a positive scenario. Here I have used the Nunit to write the tests:
If you try to run this test It will go in Infinite state:
Problem caused by the Nunit framework as it doesn’t support the methods marked with Async keyword for tests. So it kept on waiting for the asynchronous method and it actually never invokes the Task returned into start state.
Since the Nunit doesn’t actually invokes the underlying task to start state so you what you just have to do is Start the task manually.
Download the complete sample from here.