Skip to content

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.

Core skills:

  • Create an xUnit test project
  • Set up WebApplicationFactory with an in-memory database
  • Write 5–8 integration tests covering key scenarios

“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?”

  • Organize endpoints into separate files using extension methods (only if Program.cs is getting large)
  • Run tests with dotnet test and read the output
  • Test naming conventions and folder structure
  • Code coverage tools
  • Testing every possible scenario

Write integration tests for the Books API. Optionally split the code into separate endpoint files.

  1. Create a test project: dotnet new xunit -n BooksApi.Tests
  2. Add a project reference to BooksApi
  3. Install Microsoft.AspNetCore.Mvc.Testing and Microsoft.EntityFrameworkCore.InMemory
  4. Create a BooksApiFactory class that extends WebApplicationFactory<Program> and swaps in an in-memory database
  5. Write test: GET /books returns 200
  6. Write test: GET /books/{id} with a valid id returns 200
  7. Write test: GET /books/{id} with an invalid id returns 404
  8. Write test: POST /books without a token returns 401
  9. Write test: POST /books with a valid token returns 201
  10. Run all tests with dotnet test and confirm they pass
  11. Optional: Move book endpoints into a BookEndpoints.cs file using a static extension method
  • 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 test from the command line

Test project with 5–8 passing integration tests.


Week 6: Authentication | Back to Overview | Week 8: Docker