Week 7: Testing & Code Organization
Write automated integration tests so you can verify your API works correctly without manually clicking through Swagger every time. Optionally organize the code if Program.cs is getting too large.
Essential (60% of time)
Section titled “Essential (60% of time)”Core skills:
- Create an xUnit test project
- Set up WebApplicationFactory with an in-memory database
- Write 5–8 integration tests covering key scenarios
Key resources
Section titled “Key resources”- Integration Tests in ASP.NET Core
- WebApplicationFactory docs
- xUnit Getting Started
- xUnit on GitHub
- FluentAssertions
- In-Memory Database Provider
LLM prompts
Section titled “LLM prompts”“Create an xUnit test project for my Minimal API. What’s the dotnet command and what NuGet packages do I need?”
“Show me a WebApplicationFactory setup that uses an in-memory database instead of PostgreSQL.”
“Write a basic integration test: GET /books returns a 200 status code.”
“Show me one example of testing a protected endpoint. How do I generate a test JWT token and attach it to the request?”
Brief (30% of time)
Section titled “Brief (30% of time)”- Organize endpoints into separate files using extension methods (only if Program.cs is getting large)
- Run tests with
dotnet testand read the output
Optional (skip if needed)
Section titled “Optional (skip if needed)”- Test naming conventions and folder structure
- Code coverage tools
- Testing every possible scenario
Practical project
Section titled “Practical project”Write integration tests for the Books API. Optionally split the code into separate endpoint files.
Learning activities
Section titled “Learning activities”- Create a test project:
dotnet new xunit -n BooksApi.Tests - Add a project reference to BooksApi
- Install
Microsoft.AspNetCore.Mvc.TestingandMicrosoft.EntityFrameworkCore.InMemory - Create a
BooksApiFactoryclass that extendsWebApplicationFactory<Program>and swaps in an in-memory database - Write test: GET /books returns 200
- Write test: GET /books/{id} with a valid id returns 200
- Write test: GET /books/{id} with an invalid id returns 404
- Write test: POST /books without a token returns 401
- Write test: POST /books with a valid token returns 201
- Run all tests with
dotnet testand confirm they pass - Optional: Move book endpoints into a
BookEndpoints.csfile using a static extension method
Key concepts to master
Section titled “Key concepts to master”- WebApplicationFactory and how it boots your real app for testing
- Swapping PostgreSQL for an in-memory database in tests
- Making HTTP requests in tests with
HttpClient - Readable assertions with FluentAssertions:
.Should().Be() - Testing authenticated endpoints with a test Bearer token
- Running
dotnet testfrom the command line
Deliverable
Section titled “Deliverable”Test project with 5–8 passing integration tests.