Geeks With Blogs

News Please visit me at my new blog!!

profile for Aligned at Stack Overflow, Q&A for professional and enthusiast programmers
"free in Christ Jesus from the law of sin and death." Romans 8:2 (ESV) Check out the Falling Plates video on YouTube.
more about the Gospel
And then listen to Francis Chan speaking at LifeLight in SD.

Programming and Learning from SD

I needed to Fake the DbSet of a DBContext in EF 5 so that I could test my caching implementation. I searched for awhile and found this link on creating an in memory DbSet. I first copied the code in and created an InMemoryDbSet class. Then I changed all my DbSets in my DBContext to IDbSet. Then I was able to mock the call to UserProfiles and return a dummy object.

The Test

I’m using FakeItEasy which is a nuget packages.

Notice the usage of the InMemoryDbSet<UserProfile>.

public void TestInitialize()
  // mimic DataBootstrap
  ObjectFactory.Configure(registry =>
    this.usersContext = A.Fake<IUsersContext>();
    var set = new InMemoryDbSet<UserProfile> { 
    new UserProfile 
       UserName = "userName1", 
       UserId= "22" 
    A.CallTo(() => this.usersContext.UserProfiles).Returns(set);
    registry.For<IUsersContext>().Use(() => this.usersContext);
    this.mobileStarContext = A.Fake<IMobileStarContext>();
    registry.For<IMobileStarContext>().Use(() => this.mobileStarContext);
public void It_should_return_UserName_From_Configure()
    var context = ObjectFactory.GetInstance<IUsersContext>();
  using (var context = ObjectFactory.GetInstance<IUsersContext>())
    var profile = context.UserProfiles.FirstOrDefault(up => up.UserName == "userName1");
    Assert.AreEqual(22, profile.UserId);
Update on 3/11/2014:
EF6 makes this easier: How EF6 Enables Mocking DbSets more easily by Julie Lerman "But now there is another constructor. It’s protected and only uses an set interface, but not the query interface. This allows mocking frameworks to get access to DbSet and at the same time, benefit from some of the methods added to DbSet for EF6." With some MSDN links: Testing with your own test doubles (EF6 onwards) and Testing with a mocking framework (EF6 onwards)
Posted on Wednesday, December 12, 2012 11:14 AM Unit Testing , BDD , Inversion Of Control (Ioc) , Entity Framework | Back to top

Comments on this post: Mocking or Faking DbSet

# re: Mocking or Faking DbSet
Requesting Gravatar...
Greetings! I've been following your weblog for some time now and finally got the courage to go ahead and give you a shout out from Atascocita Texas! Just wanted to say keep up the good work!
future stock
Left by ray12 on Jun 09, 2013 11:35 AM

Your comment:
 (will show your gravatar)

Copyright © Aligned | Powered by: