23 Testing your application

 

This chapter covers

  • Creating unit test projects with xUnit
  • Writing unit tests for custom middleware and API controllers
  • Using the Test Host package to write integration tests
  • Testing your real application’s behavior with WebApplicationFactory
  • Testing code dependent on EF Core with the in-memory database provider

When I first started programming, I didn’t understand the benefits of automated testing. It involved writing so much more code—wouldn’t it be more productive to be working on new features instead? It was only when my projects started getting bigger that I appreciated the advantages. Instead of having to manually run my app and test each scenario, I could press Play on a suite of tests and have my code tested for me automatically.

Testing is universally accepted as good practice, but how it fits into your development process can often turn into a religious debate. How many tests do you need? Is anything less than 100% coverage of your code base adequate? Should you write tests before, during, or after the main code?

23.1 An introduction to testing in ASP.NET Core

23.2 Unit testing with xUnit

23.2.1 Creating your first test project

23.2.2 Running tests with dotnet test

23.2.3 Referencing your app from your test project

23.2.4 Adding Fact and Theory unit tests

23.2.5 Testing failure conditions

23.3 Unit testing custom middleware

23.4 Unit testing API controllers

23.5 Integration testing: Testing your whole app in-memory

23.5.1 Creating a TestServer using the Test Host package

23.5.2 Testing your application with WebApplicationFactory

23.5.3 Replacing dependencies in WebApplicationFactory

23.5.4 Reducing duplication by creating a custom WebApplicationFactory

23.6 Isolating the database with an in-memory EF Core provider

Summary