EF4 - possible to mock ObjectContext for unit testing?

此生再无相见时 提交于 2019-12-18 16:49:39

问题


Can it be done without using TypeMock Islolator? I've found a few suggestions online such as passing in a metadata only connection string, however nothing I've come across besides TypeMock seems to truly allow for a mock ObjectContext that can be injected into services for unit testing. Do I plunk down the $$ for TypeMock, or are there alternatives? Has nobody managed to create anything comparable to TypeMock that is open source?


回答1:


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 the IRepository interface. I then replaced the IObjectSet<T> with a List<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.




回答2:


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!




回答3:


Wrap the ObjectContext in a proxy class. Then inject that into your classes.




回答4:


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



来源:https://stackoverflow.com/questions/2703100/ef4-possible-to-mock-objectcontext-for-unit-testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!