chapter seventeen

17 Unit testing EF Core applications

 

This chapter covers

  • The three ways to simulate a database for unit testing
  • Using the databases type as your production app for unit testing
  • The pros and cons of 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 when 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 very useful and I use it a lot. It makes me a better developer because I can catch bugs both while I’m developing the code and, more importantly, when I refactor the code.

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

17.1  An introduction to the unit test setup

17.1.1         The test environment—the xUnit unit test library

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

17.2  Getting your application’s DbContext ready for unit testing

17.2.2         Setting an application’s DbContext options via OnConfiguring

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

17.5.3         Making sure the database’s schema is up to date and the database is empty

17.5.4         Mimicking the database setup that the Migrate provides

17.6  Using SQLite in-memory database for unit testing

17.7  Mocking a database repository pattern

17.8  Unit testing a Cosmos DB database

17.10     Solving the problem of one database access breaking another part of your test

17.10.1     Test code using ChangeTracker.Clear in a disconnected state

17.10.2     Test code using multiple DbContext instances in a disconnected state

17.12     Summary