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

查看:13
本文介绍了如何模拟 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 既不是抽象也不是接口,因此模拟它并不容易.但是,由于具体模型容器是作为部分类生成的(如果您使用设计器),您可以从中提取所需的方法/属性到接口.在您的代码中,您只能使用接口,之后可以模拟.

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