如何模拟ObjectContext的或的ObjectQuery< T>在实体框架? [英] How to mock ObjectContext or ObjectQuery<T> in Entity Framework?

查看:156
本文介绍了如何模拟ObjectContext的或的ObjectQuery< T>在实体框架?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何模拟ObjectContext的或的ObjectQuery实体框架?

How to mock ObjectContext or ObjectQuery in Entity Framework?

推荐答案

基本的嘲弄框架只能创建嘲弄的接口和抽象类(但仅限于抽象/虚拟方法)。

The basic mocking frameworks can only create mocks for interfaces and for abstract classes (but only for abstract/virtual methods).

由于ObjectContext的既不是抽象的,也不接口,它是不那么容易模拟它。然而,由于具体的模型容器中产生的部分类(如果您使用设计器),你可以提取你从它需要一个接口中的方法/属性。在您的code,您可以使用该接口而已,日后可以嘲笑。

As the ObjectContext is neither abstract nor interface, it is not so easy to mock it. However, as the concrete model container is generated as partial class (if you use the designer), you can extract the methods/properties you need from it to an interface. In your code, you may use the interface only, that you can mock afterwards.

随着的ObjectQuery它更容易一点,因为它有一个基本接口(如IQueryable的),基本上包含了所有留点作业,你通常需要(和所需的LINQ)。所以,你应该揭露IQueryable的,而不是在的ObjectQuery你的业务逻辑,并可以为该接口创建模拟。

With the ObjectQuery it is a little bit more easy, as it has a base interface (e.g. IQueryable) that basically contains all the neccessary operations that you usually need (and required for LINQ). So you should expose IQueryable instead of ObjectQuery in your business logic, and you can create mock for that interface.

的其它替代方案是隐藏所有数据访问相关的逻辑到一个单独的层(以最小的逻辑),测试此层与集成测试,并模拟它能够单元测试的其他层。

Other alternative is to hide all data-access related logic into a separate layer (with minimal logic), test this layer with integration tests, and mock it to be able to unit test the other layers.

有工具(我只知道 TypeMock )使用.NET的分析挂钩产生的嘲笑。这些工具不仅限于模拟接口或抽象类,但它们可以模拟基本上什么包括非虚拟和静态方法。有了这样一个工具,你不需要改变你的商业逻辑,为了让嘲讽。

There are tools (I know only TypeMock) that use the profiling hooks of .NET to generate the mocks. These tools are not limited to mock interfaces or abstract classes, but with them you can mock basically anything, including non-virtual and static methods. With such a tool you don't need to change your business logic in order to allow mocking.

虽然这种方法有时是有用的,你必须要知道,提取依赖于接口(IOC)不仅是嘲讽有帮助,同时也降低了依赖的组件之间,它有其他好处。

Although this approach is sometimes useful, you have to be aware that extracting the dependencies to interfaces (IoC) is not only helpful for mocking, but also it reduces the dependencies between your components, that has other benefits too.

我个人喜欢 Rhino.Mocks 最好的免费软件工具,但我们也使用的TypeMock 为好,这也是一个伟大的产品(但你必须为此付出代价)。

Personally I like Rhino.Mocks the best from the freeware tools, but we also use TypeMock as well, which is also a great product (but you have to pay for it).

这篇关于如何模拟ObjectContext的或的ObjectQuery< T>在实体框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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