Lesson 23 / 26
Testing with xUnit
Write unit tests and an in-memory integration test using WebApplicationFactory.
Two kinds of tests
Unit tests check one class with fakes for its dependencies and run in milliseconds. Integration tests start the real app pipeline in memory with WebApplicationFactory<Program> and send HTTP requests to it. Use many of the first and a few of the second.
A unit test and an API test
Add public partial class Program { } at the end of Program.cs so the test project can see it. Run everything with dotnet test.
public class GreeterTests
{
[Fact]
public void Greet_ReturnsGreeting()
=> Assert.Equal("Hello, Asha!", new Greeter().Greet("Asha"));
}
public class ApiTests(WebApplicationFactory<Program> factory)
: IClassFixture<WebApplicationFactory<Program>>
{
[Fact]
public async Task Root_ReturnsOk()
{
var res = await factory.CreateClient().GetAsync("/");
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
}
}Test behaviour, not wiring
Tests that mirror the implementation line by line break on every refactor. Assert on results a caller can see: status codes, response bodies and saved data.
Quick check: What does WebApplicationFactory<Program> provide?
- An in-memory test server running your app
- A production load balancer
- A database schema generator
- A code formatter
Answer
An in-memory test server running your app — It hosts your real pipeline in the test process so you can call it with an `HttpClient`.