This post is about unit testing ASP.NET MVC 6 applications. Unlike MS Test, this post is using XUnit Framework, which is the currently used unit testing framework for ASP.NET 5 applications.
Similar to TestMethod, XUnit uses Fact / Theory attributes. You can find more comparison details here.
Unit testing class libraries
Here is the unit tests for calculator class, with Add method.
And here is source code
Similar to ASP.NET 5 applications, unit test project also requires a project.json file.
You need to execute the kpm restore command to download the XUnit runner, once it is finished, you can execute k test command to execute the tests. XUnit test runner will display result like this.
If you looked into the XUnit test results you can see something like Total :3, it because of the Theory and InlineData attributes, XUnit will treat the test method as a different one.
Unit testing MVC Controllers
Unlike class libraries, MVC controllers are little difficult to unit test. As controllers contains business logic and database interactions, you need to decouple it and inject it. This project is an ASP.NET MVC 6 project, code is generated using ASP.NET Scaffolding, it uses Entity Framework 7.0 and SQL Server localDb for database operations. In solution I wrote code to decouple the database interaction using repository pattern.
Here is the controller class.
I am using ASP.NET dependency injection framework for injecting the repository class to the controller. You can find more details about ASP.NET dependency injection here
And here is my index method, which returns employees from the database using repository.
And here is the unit test for the same. I am using Moq framework for mocking the
As XUnit doesn’t have equivalents for Test Initialize / Class Initialize / Setup / Teardown, I have wrote the code to setup the controller and mocks in the test class constructor.
As part of Index action, we are returning model object(Employee list), if we didn’t set ViewData property, tests will fail, with Null reference exception. This is because the controller class internally uses the ViewData property to return the Model to the view, while running controller from Unit test context, ASP.NET runtime won’t inject the required services to the view data property, so you need to set it manually.
Here is the Details action.
And here is the unit tests for the same.
Most of the above tests are pretty straight forward, you can understand pretty easily. Here is the create action method.
And unit tests for the Create method. One problem with the create method is that, it is using ModelState property of controller class to validate the model. As the model class is using Data Annotations API for validating the model, it is very difficult to mock. So we need to use the actual property to mock validation errors.
This code
is used to mock the model validation error. XUnit running on the tests