Posts

Showing posts from October, 2012

Unit Testing with a Mock Entity Framework DbContext and Fake DbSets

I'm a big fan of the Repository pattern, and use it hand-in-hand with dependency injection and the Query Object pattern. Lately I've been developing with Entity Framework, and using dependency injection to pass the DbContext instances into my repository classes. But one of the issues I ran into while trying to unit test one of my repository classes is that I couldn't figure out how to mock the DbSets that my DbContext exposes. I could create a mock of the DbContext, but was having trouble setting it up to return fake collections of entities. One of the problems is that DbSet has no constructor (it's created via a factory method). After much research and scouring of the web, here are the steps I learned to accomplish this.   Step One: Create a Fake DbSet Class That Implements IDbSet The DbContext exposes entities in DbSets. DbSet, in turn, implements the IDbSet interface. So we can create a class for use with our unit tests that, unlike DbSet, can be instantiated on ...