Is it possible to stub Entity Framework context an

2020-07-24 03:09发布

问题:

I'm familiar with techniques used for testing controllers and business logic in ASP .NET MVC application.

Data access in our app is concentrated in special services which are loosely coupled, use interfaces and work with actual database through Entity Framework.

However, as DAL became increasingly more complex, hiding away database implementation details and providing application code with abstractions, we became concerned if we are able to test it by any means. Because it is already tightly bound to EF context, we don't plan to introduce yet another repository-style layer, however this also means we can't just unit-test it with fake data.

I'm wondering if it's possible to somehow mock or stub Entity Framework object context while being able to do simple operations like adding/deleting entities and making queries.

I'm also looking for opinion on whether it is a good idea at all (perhaps really bad), and if it isn't, some 'smart' data layer testing advice.

回答1:

Mocking / stubbing EF is partially possible if you use IObjectSet and custom interface for your derived ObjectContext instance and all your EF dependent code will access EF features only through these interfaces (context will be injected). Every other EF related features must be hidden in methods exposed on object context interface.

I discussed in several answers (for example here and here) that this really doesn't help because you don't test the real code. The very big problem is that once you mock / stub EF code you are replacing linq-to-entities with linq-to-objects. Another problem is that you are losing referential integrity for persisting entities. Because of that I believe that DAL, persistence and querying should be covered with integration tests using real EF with real DB.