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.
Marking as completed as we have made advances in EF Core towards this (and we did previously in EF6) and we don’t plan to go any further.
In general we recommend against trying to mock EF API behaviors beyond simple cases because they are too complex and dependent on the underlying providers and databases. Instead we recommend either using in-memory databases or creating abstractions such as repositories in applications, which can be more easily mocked.
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.