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

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

问题描述

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

解决方案

基本的嘲笑框架只能为接口和抽象类(但仅适用于抽象/虚拟方法)。



由于ObjectContext既不是抽象的也不是接口,它不是那么容易嘲笑它。但是,由于具体的模型容器是作为部分类生成的(如果使用设计器),则可以将所需的方法/属性从其中提取到接口。在你的代码中,你可以只使用这个接口,以后你可以模仿它。



使用ObjectQuery有一点点简单,因为它有一个基本接口例如IQueryable),它基本上包含您通常需要的所有必需操作(并且需要LINQ)。因此,您应该在业务逻辑中公开IQueryable而不是ObjectQuery,您可以为该界面创建模拟器。



另一种方法是将所有与数据访问相关的逻辑隐藏到单独的层(最小的逻辑),用集成测试测试这个层,并模拟它能够单元测试其他层。



有工具(我只知道 TypeMock ),它们使用.NET的分析钩子来生成嘲笑。这些工具不仅限于模拟界面或抽象类,而且可以基本上模拟任何内容,包括非虚拟和静态方法。使用这样的工具,您不需要更改业务逻辑,以便嘲笑。



尽管这种方法有时是有用的,但您必须注意提取对接口的依赖(IoC)不仅有助于嘲笑,而且还减少了组件之间的依赖关系,这也有其他好处。



我个人喜欢 Rhino.Mocks 最好的免费工具,但我们也使用 TypeMock ,这也是一个很棒的产品(但你必须支付)。


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).

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.

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.

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.

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.

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天全站免登陆