Testing the database access layer
In many web API applications, we need to access the database to perform CRUD operations. In this section, we will learn how to test the database access layer in unit tests.
How can we test the database access layer?
Currently, we inject InvoiceDbContext
into controllers to access the database. This approach is easy for development, but it tightly couples the controllers with the InvoiceDbContext
class. When we test the controllers, we need to create a real InvoiceDbContext
object and use it to test the controllers, which means controllers are not tested in isolation. This problem can be addressed in a variety of ways:
- Use the
InMemoryDatabase
provider of EF Core to create an in-memory database as the fake database - Use the SQLite in-memory database as the fake database
- Create a separate repository layer to encapsulate the database access code, inject the repository layer into controllers (or services that need to access databases...