Lessons in this course (12)

9. Test pyramid, integration tests and TDD

Intermediate★ Must knowLesson 9 of 12

Test pyramid: many fast unit tests → fewer integration tests (API + real DB) → few end-to-end/UI tests (Playwright/Selenium).

csharp
// Integration test with WebApplicationFactory
public class OrdersApiTests(WebApplicationFactory<Program> factory) : IClassFixture<WebApplicationFactory<Program>>
{
    [Fact]
    public async Task Get_unknown_order_returns_404()
    {
        var client = factory.CreateClient();
        var res = await client.GetAsync("/api/orders/999999");
        Assert.Equal(HttpStatusCode.NotFound, res.StatusCode);
    }
}

TDD cycle — Red, Green, Refactor: write a failing test → write the minimum code to pass → clean up. Benefits: testable design, a safety net, living documentation.

Code coverage: a useful signal, not a goal. 80% coverage of meaningful branches beats 100% of trivial getters. Mutation testing (Stryker) checks whether tests actually catch bugs.