36 Testing ASP.NET Core applications

 

This chapter covers

  • Writing unit tests for custom middleware, API controllers, and minimal API endpoints
  • Using the Test Host package to write integration tests
  • Testing your real application’s behavior with WebApplicationFactory
  • Testing code dependent on Entity Framework Core with the in-memory database provider

In chapter 35 I described how to test .NET 7 applications using the xUnit test project and the .NET Test software development kit (SDK). You learned how to create a test project, add a project reference to your application, and write unit tests for services in your app.

In this chapter we focus on testing ASP.NET Core applications specifically. In sections 36.1 and 36.2 we’ll look at how to test common features of your ASP.NET Core apps: custom middleware, API controllers, and minimal API endpoints. I show you how to write isolated unit tests for both, much like you would any other service, and I’ll point out the tripping points to watch for.

36.1 Unit testing custom middleware

36.2 Unit testing API controllers and minimal API endpoints

36.3 Integration testing: Testing your whole app in-memory

36.3.1 Creating a TestServer using the Test Host package

36.3.2 Testing your application with WebApplicationFactory

36.3.3 Replacing dependencies in WebApplicationFactory

36.3.4 Reducing duplication by creating a custom WebApplicationFactory

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

Summary

sitemap