ASP.NET Core MVC Advanced

Integration tests

Integration tests run your whole app in memory and send it real HTTP requests, so routing, middleware, filters, controllers and views are all tested together. This lesson shows WebApplicationFactory and how to swap in a test database.

How an integration test runs
  1. StartTest creates the factoryWebApplicationFactory<Program> boots your app
  2. Step 2App runs in memoryTestServer instead of a real network port
  3. Step 3Services swappedA test database or fake email sender replaces the real ones
  4. Step 4HttpClient sends requestsGET /products, POST forms, follow redirects
  5. Step 5Full pipeline runsMiddleware, routing, filters, controllers, views
  6. EndAssertStatus codes, headers and the HTML returned

The idea in plain words

Unit tests prove each piece works alone; integration tests prove the pieces work together. The Microsoft.AspNetCore.Mvc.Testing package provides WebApplicationFactory, which starts your real Program.cs with an in-memory TestServer and gives you an HttpClient connected to it.

You can override configuration and services for the test, for example pointing EF Core at a test database. If your test project cannot see the Program class, add public partial class Program { } at the end of Program.cs.

Example

IClassFixture shares one factory between the tests in a class, so the app starts once.

C#
public class ProductPagesTests : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly WebApplicationFactory<Program> _factory;

    public ProductPagesTests(WebApplicationFactory<Program> factory)
    {
        _factory = factory.WithWebHostBuilder(builder =>
            builder.ConfigureTestServices(services =>
            {
                services.AddScoped<IEmailSender, FakeEmailSender>();
            }));
    }

    [Fact]
    public async Task Products_page_loads()
    {
        var client = _factory.CreateClient();

        var response = await client.GetAsync("/products");

        response.EnsureSuccessStatusCode();
        var html = await response.Content.ReadAsStringAsync();
        Assert.Contains("<h1>Products</h1>", html);
    }

    [Fact]
    public async Task Orders_page_requires_sign_in()
    {
        var client = _factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false });

        var response = await client.GetAsync("/orders");

        Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
        Assert.Contains("/Account/Login", response.Headers.Location!.ToString());
    }
}

Common mistakes

  • Running integration tests against a shared real database, so tests interfere with each other. Use a separate test database or a container per test run.
  • Forgetting that POST tests must include a valid anti-forgery token; read it from the form page first.
  • Testing every small rule with integration tests; keep those for unit tests and use integration tests for the important paths.

Interview question

What is the difference between unit tests and integration tests in ASP.NET Core?

Unit tests exercise a single class or method in isolation, such as a controller action with fake dependencies, and are fast and precise. Integration tests run the application, or a large part of it, with real infrastructure such as the middleware pipeline, routing, filters, views and often a database, typically through WebApplicationFactory and TestServer, to verify that components work together.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.