是否可以存放Entity Framework上下文和类来测试数据访问层? [英] Is it possible to stub Entity Framework context and classes to test data access layer?

查看:139
本文介绍了是否可以存放Entity Framework上下文和类来测试数据访问层?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我熟悉ASP.NET MVC应用程序中用于测试控制器和业务逻辑的技术。



我们的应用程序中的数据访问集中在特殊服务松散耦合,使用接口并通过实体框架与实际数据库一起工作。



然而,随着DAL变得越来越复杂,隐藏了数据库实现细节并提供了抽象的应用程序代码,如果我们能够以任何方式测试,我们就变得担心。因为它已经紧密地绑定到EF上下文,所以我们不打算再引入另一个存储库样式层,但这也意味着我们不能单独使用假数据进行单元测试。



我想知道,如果可以以某种方式模拟或存储Entity Framework对象上下文,同时能够执行简单的操作,如添加/删除实体和进行查询。



我也在寻找关于它是否是一个好主意(可能真的很糟糕)的意见,如果不是,一些聪明的数据层测试建议

解决方案

如果您使用 IObjectSet 和自定义接口为您的派生 ObjectContext 实例,所有EF依赖代码只能通过这些接口访问EF功能(将注入上下文)。在对象上下文界面中暴露的方法中必须隐藏其他EF相关的功能。



我在几个答案中讨论过(例如这里 here ),这真的没有帮助,因为你没有测试真正的代码。一个很大的问题是,一旦你模拟/存根EF代码,你正在用linq-to-objects替换linq-to-entity。另一个问题是您正在失去持久实体的引用完整性。因为我相信DAL,持久性和查询应该使用真正的EF与真实DB的集成测试来覆盖。


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.

解决方案

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.

这篇关于是否可以存放Entity Framework上下文和类来测试数据访问层?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆