Is it possible to stub Entity Framework context and classes to test data access layer?

有些话、适合烂在心里 提交于 2019-12-13 12:15:33

问题


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.



来源:https://stackoverflow.com/questions/6262588/is-it-possible-to-stub-entity-framework-context-and-classes-to-test-data-access

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!