Microsoft has introduced a new library for integration testing Microsoft.AspNetCore.Mvc.Testing as a part of the asp.net core 2. In the previous version of the .net framework, I have used Microsoft.Owin.Testing package for doing the integration test and this seems like a logical extension to the same with some batteries included.

In this Blog Post, Let me show how to get started by using the library and apply a few best practices which I have learned in the past few days.

Getting Started :

As with any good .net library, you can download it using NuGet.

It includes a new WebApplicationFactory that I point to my app’s Startup class. Now I can create my HttpClient with the CreateDefaultClient() method .

This Httpclient has defaulted to localhost, but we can change the default configuration using CreateClient() method.

Best Practices :

As you have seen, I have used IClassFixture<T> and injected the WebApplicationFactory<TStartup> in the constructor. Xunit uses this pattern to dispose of the object once it runs all the test fixture. Always dispose of the WebApplicationFactory object and don’t try to share it with multiple classes. Create your own asp.net core environment for better Test isolation.

As shown code, we can override the Asp.net core environment settings by deriving from the WebApplicationFactory class.

We can use this environment settings to incorporate some settings like the InMemory Entity framework or Moq few external dependencies.

Here are a few references I have used.