249
CHAPTER 6 | Tackle Business Complexity in a Microservice with DDD and CQRS Patterns
Figure 7-18. Using custom repositories versus a plain DbContext
Figure 7-18 shows that using a custom repository adds an abstraction layer that can be used to ease
testing by mocking the repository. There are multiple alternatives when mocking. You could mock just
repositories or you could mock a whole unit of work. Usually mocking just the repositories is enough,
and the complexity to abstract and mock a whole unit of work is usually not needed.
Later, when we focus on the application layer, you will see how Dependency Injection works in
ASP.NET Core and how it is implemented when using repositories.
In short, custom repositories allow you to test code more easily with unit tests that are not impacted
by the data tier state. If you run tests that also access the actual database through the Entity
Framework, they are not unit tests but integration tests, which are a lot slower.
If you were using DbContext directly, you would have to mock it or to run unit tests by using an in-
memory SQL Server with predictable data for unit tests. But mocking the DbContext or controlling
fake data requires more work than mocking at the repository level. Of course, you could always test
the MVC controllers.
Dostları ilə paylaş: