Make Entity Framework fully mockable and injectable
Make Entity Framework Fully Mockable and injectable
In general, mocking out the Entity Framework DAL is a big pain to accomplish. ObjectContext has no interface and the T4 templates aren't written to create interfaces for the objects they create.
This hampers good unit testing and makes them less injectable.
Put an interface on ObjectContext. Have the T4 Templates put interfaces around all of the objects that are generated and make sure that all objects used have interfaces so that mocking frameworks, like MOQ or Moles & Pex can automatically generate stubs to replace the objects in unit tests so that tests don't need to be tightly coupled to the database.
We made some improvements in this direction in EF6. Here is the documentation section on how to take advantage of them: http://msdn.microsoft.com/en-us/dn314429
Nobody Real commented
More important than interfaces is creating a mockable IQueryable that has the same code generation semantics. Merely using Linq ot Objects has lots of gotchas.
At the time of writing this, It's already got 370+ points in VS feature suggestions : http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2466931-make-entity-framework-fully-mockable-and-injectable
Martín Coll commented
Hi, I came here to ask this too. I think I'll do this http://blogs.planetcloud.co.uk/mygreatdiscovery/post/EF-Code-First-Common-Practices.aspx, put it's pretty hacky.
IObjectContext and IDbContext interfaces would help a lot in mocking with frameworks like Moq.