15 Unit testing EF Core applications

 

This chapter covers

  • Simulating a database for unit testing
  • Using an in-memory database for unit testing
  • Using real databases for unit testing
  • Unit testing a disconnected state update
  • 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 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.

Unit testing is a big subject, with whole books dedicated to the topic. I focus on the narrow, but important, area of unit-testing applications that use EF Core for database accesses. To make this chapter focused, I don’t explain the basics of unit testing, but leap right in. I therefore recommend anyone new to unit testing to skip this chapter, or come back to it after you’ve read up on the subject. This chapter won’t make any sense without that background, and I don’t want to discourage you from unit testing because I make it look too hard.

Tip

To learn more about unit testing, have a look at https://msdn.microsoft.com/en-us/library/hh694602.aspx. For much more in-depth coverage of unit testing, I recommend Roy Osherove’s The Art of Unit Testing: with Examples in C#, Second Edition (Manning, 2013), http://mng.bz/1f92.

15.1 Introduction—our unit test setup

15.1.1 The test environment—the xUnit unit test library

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

15.2 Simulating the database when testing EF Core applications

15.2.1 The options you have for simulating the database

15.2.2 Choosing between an in-memory or real database for unit testing

15.3 Getting your application’s DbContext ready for unit testing

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

15.3.2 Setting an application’s DbContext options via OnConfiguring

15.4 Simulating a database—using an in-memory database

15.5 Using a real database in your unit tests

15.5.1 How to set up a real database for unit testing

15.5.2 Running unit tests in parallel—uniquely named databases

15.5.3 Tips on how to speed up the database creation stage of a unit test

15.5.4 How to handle databases in which you’ve added extra SQL code

15.6 Unit testing a disconnected state update properly

15.7 Mocking a database repository pattern

15.8 Capturing EF Core logging information in unit testing

15.8.1 Using logging to help you build SQL change scripts

15.9 Using the EfSchemaCompare tool in your unit tests

15.9.1 Features and options for the EfSchemaCompare tool

Summary

sitemap