liveBook · Manning

WithWebHostBuilder

As explained in ASP.NET Core in Action, 3e

WithWebHostBuilder is a WebApplicationFactory method that returns a customized test factory configured through an application host builder.

WithWebHostBuilder customizes a WebApplicationFactory before its in-memory TestServer starts. It returns a new factory, leaving the original fixture unchanged. section 36.3.3

Use it to adjust one integration test without changing the real application:

  • Call ConfigureTestServices inside the host-builder callback. section 36.3.3
  • Remove or replace registered dependencies, such as a third-party API client. section 36.5
  • Create the client from the returned factory and send requests against the in-memory application. section 36.3.3

Replacing a currency converter for one test

A test can call _fixture.WithWebHostBuilder(builder => builder.ConfigureTestServices(services => { services.RemoveAll<ICurrencyConverter>(); services.AddScoped<ICurrencyConverter, StubCurrencyConverter>(); })); The returned factory uses the stub while other tests retain the original fixture configuration. section 36.3.3

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains factory isolation and service-order behavior, then stops short of detailed host-builder internals.
Examples
Replaces ICurrencyConverter with StubCurrencyConverter and verifies a currency API response.
What it assumes
Assumes familiarity with WebApplicationFactory, IClassFixture, dependency injection, and ASP.NET Core integration tests.
What you can do after
Apply it via WebApplicationFactory to replace services for an individual integration test.
How it connects
Connects WebApplicationFactory, TestServer, dependency injection, ConfigureTestServices, integration testing, and custom WebApplicationFactory.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.