Integration testing in ASP.NET MVC 6

By Dawid on (tags: asp.net 5, mvc 6, testing, categories: code)

In ASP.NET 5, Microsoft has produced a Nuget package called Microsoft.AspNet.TestHost which you can easily use to run your ASP.NET 5 in memory. We can use that feature of self hosted application to create integration tests.

Creating integration test project

After creating a new ASP.NET 5 solution open file and dependency for XUnit.DNX integration packages and the Microsoft.AspNet.TestHost package. Here is an example file:

After this we are ready to write simple controller which we use in our tests. Take a look at this:

We will use class which exposes a lot of factory methods depending on how much set up you want to do. The server will be created as http://localhost unless you set the BaseAddress property to something else. In fact the URL is not so important as long as server and client agree on the save value. As I mentioned before, the factory methods on the TestServer make it easy to integrate your Startup class into the tests. Here is an example of class which will set up our tests:

And here are out simple integration tests – we will test our example controller created above:

And that’s all. As you can see this approach is very simple and what’s worth mentioning - all end-to-end tests in the MVC 6 repository use the same approach!