Core Integration Test

Microsoft has introduced a new library for integration testing Microsoft.AspNetCore.Mvc.Testing as a part of the 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 :

  1. 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.
  2. Always dispose of the WebApplicationFactory object and don’t try to share it with multiple classes.
  3. Create your own core environment for better Test isolation.

As shown code, we can override the 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.

I build intelligent Web Apps