When Microsoft designed ASP.NET Core, testability was a core design goal. Using dependency injection, you can unit test your middlewares and controllers. You can also use TestServer for integration tests, which lets you test your entire web application without IIS or any external infrastructure. It runs fully in-process. Consider the following example:
C#
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMvc();
}
}
[Route("api/[controller]")]
public class ValuesController : Controller
{
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
- Add a new MSTest project
- Add a reference to the web project
- Add the NuGet package:
Microsoft.AspNetCore.TestHost - Create a test
C#
[TestClass]
public class Tests
{
[TestMethod]
public async Task TestMethod1()
{
var webHostBuilder =
new WebHostBuilder()
.UseEnvironment("Test") // You can set the environment you want (development, staging, production)
.UseStartup<Startup>(); // Startup class of your web app project
using (var server = new TestServer(webHostBuilder))
using (var client = server.CreateClient())
{
string result = await client.GetStringAsync("/api/values");
Assert.AreEqual("[\"value1\",\"value2\"]", result);
}
}
}
This is a basic example. In a more complex scenario, you may want to replace services using DI. ASP.NET Core supports multiple environments out of the box. For instance, you can define a Configure<EnvironmentName>Services method per environment. If no method is defined for the current environment, ConfigureServices is used as the fallback. One approach to customize DI for testing is to create a class that inherits from Startup and add a ConfigureTestServices method:
C#
public class TestStartup : Startup
{
public TestStartup(IHostingEnvironment env) : base(env)
{
}
public void ConfigureTestServices(IServiceCollection services)
{
// Configure services for Test environment
}
}
Then, use the TestStartup class to initialize the TestServer:
C#
[TestMethod]
public async Task TestMethod1()
{
var webHostBuilder =
new WebHostBuilder()
.UseEnvironment("Test")
.UseStartup<TestStartup>();
// ...
}
Visual Studio Test Explorer
This is a brief introduction to integration testing with ASP.NET Core. You can find more resources in the documentation.
Do you have a question or a suggestion about this post? Contact me!