.NetASP.NetASP.Net MVCEntity FrameworkUnit TestingWeb API
This post is about unit testing Web API controller. As we are using Entity Framework and some Web API related classes, we need to implement dependency injection to unit test Web API controllers.
To manage Entity Framework dependency, I am using a simple Repository pattern. Here is my repository interface.
As this post is more focusing on unit testing, I am not including the implementation of the IRepository interface, it is same as we used in the controller. And I am modified the controller like this, one more constructor added, which accepts IRepository as one parameter.
And the Get methods in the controller is modified like this.
Instead of using Entity Framework directly, interacting to DB via Repository. You can write the unit test like this to verify the Get method.
For mocking purposes I am using Moq library. As we are using the Request property to create the HttpResponseMessage, you need to set a default value to the request property, otherwise you will get some null reference exception from the unit test.
Similar to Request property, in the post method we are using the Url property from APIController class, which is an instance of the UrlHelper class. Unlike the Request property, Url property is quite complex to create, so I am using a wrapper class, which will wraps the Url.Link() method. And I created an interface like this.
And the implementation is like this.
To use the IUrlHelper interface, I modified the controller class again like this.
Both Post and Put method modified to use _urlHelper, instead of the Url property.
Here is the test method for verifying the Post method in the controller.
You can write similar tests for all the other methods.