views:

908

answers:

2

I'm using the entity framework to access my database and I want to mock the database context inside my unit tests so that I can test my middle tier classes free of their dependency on real data. I know that I'm not the first to ask about this (Mocking an Entity Framework Model), but after some googling I have an instinct that it might be possible to instantiate the context based on the model's metadata alone.

Has anyone been able to do this?

+1  A: 

You can do it with just metadata, there's a good article on it, and unit testing EF in general, here.

Steven Robbins
+3  A: 

A well known way of doing this is to use the Repository pattern. This acts as a layer over your concrete data access implementation and provides a place to inject test doubles.

Andrew Peters
Even with the repository pattern (which is definately a good idea) you may still want to keep an ObjectContext around to take advantage of it.
Steven Robbins
The repository patterns I've seen for EF use the ObjectContext internally.
Dave Swersky
The ObjectContext should usually injected into repositories as a dependency - Repository and Unit of Work are orthogonal.
Andrew Peters