EF4 - 可以模拟 ObjectContext 进行单元测试吗?
不使用TypeMock Islolator可以完成吗?我在网上找到了一些建议,例如传递仅元数据连接字符串,但是除了 TypeMock 之外,我遇到的没有任何东西似乎真正允许将模拟 ObjectContext 注入到服务中以进行单元测试。我是否要花很多钱购买 TypeMock,还是有其他选择?没有人设法创建任何与开源 TypeMock 相媲美的东西吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我可以轻松地对 EF4 进行单元测试,而无需进行模拟。我所做的是使用 http://elegantcode.com/2009/12/15/entity-framework-ef4-generic-repository-and-unit-of-work-prototype/ 为基础然后,我创建了一个使用
IRepository
接口的InMemoryRepository
类。然后,我用类内部的List
替换了IObjectSet
并相应地更改了检索方法。因此,如果您需要进行单元测试,请传入 InMemoryRepository 而不是 DataRepository。
I'm unit testing EF4 easily without mocking. What I did was create a repository interface using the code from http://elegantcode.com/2009/12/15/entity-framework-ef4-generic-repository-and-unit-of-work-prototype/ as a basis I then created an
InMemoryRepository<T>
class that used theIRepository
interface. I then replaced theIObjectSet<T>
with aList<T>
inside of the class and changed the retrieval methods accordingly.Thus if you need to do unit testing, pass in the InMemoryRepository rather than the DataRepository.
将您的 Linq2Entity 查询放在接口后面,针对真实数据库单独进行单元测试。
使用查询接口的模拟为您的业务逻辑编写测试。不要让 Linq 渗透到您的业务逻辑中!
不要使用存储库模式!
Put your Linq2Entity query behind an interface, unit test it in isolation against a real database.
Write tests for your business logic with mocks for your query interfaces. Don't let Linq bleed into your business logic!
Don't use the RepositoryPattern!
将 ObjectContext 包装在代理类中。然后将其注入到您的课程中。
Wrap the ObjectContext in a proxy class. Then inject that into your classes.
我不认为存储库模式是问题的唯一答案(当然,它避免了问题)
我喜欢这个答案 - 我认为更适合向现有代码库引入测试 为 ObjectContext 创建接口
I don't think the repository pattern is the only answer to the question (it avoids the problem, sure)
I liked this answer - I think more appropriate for introducing tests to an existing codebase Creating Interface for ObjectContext