17 Unit testing EF Core applications

 

This chapter covers

  • Simulating a database for unit testing
  • Using the database type as your production app for unit testing
  • Using an SQLite in-memory database for unit testing
  • Solving the problem of one database access breaking another part of your test
  • Capturing logging information while unit testing

This chapter is about unit testing applications that use EF Core for database access. You’ll learn what unit testing approaches are available for working with EF Core and how to choose the correct tools for your specific needs. I also describe numerous methods and techniques to make your unit testing both comprehensive and efficient. Personally, I think unit testing is useful, and I use it a lot. It makes me a better developer because I can catch bugs both when I develop the code and, more important, when I refactor the code.

But although I really like unit testing, I’m also aware that writing unit tests takes development effort, including refactoring unit tests as the application grows. Over the years, I have learned a lot of tips and techniques for unit testing, and I have built a library called EfCore.TestSupport to help me, and you, write unit tests quickly and efficiently.

17.1 An introduction to the unit test setup

17.1.1 The test environment: xUnit unit test library

17.1.2 A library I created to help with unit testing EF Core applications

17.2 Getting your application’s DbContext ready for unit testing

17.2.1 The application’s DbContext options are provided via its constructor

17.2.2 Setting an application’s DbContext options via OnConfiguring

17.3 Three ways to simulate the database when testing EF Core applications

17.4 Choosing between a production-type database and an SQLite in-memory database

17.5 Using a production-type database in your unit tests

17.5.1 Providing a connection string to the database to use for the unit test

17.5.2 Providing a database per test class to allow xUnit to run tests in parallel