Geeks With Blogs

News Infragistics JQuery Advertisement
----------------
profile for Aligned at Stack Overflow, Q&A for professional and enthusiast programmers

Check out Elapser from T3rse!
"free in Christ Jesus from the law of sin and death." Romans 8:2 (ESV) Check out the Falling Plates video on YouTube.
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>.

[TestInitialize]
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);
  };
}
[TestMethod]
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.IsNotNull(profile);
    Assert.AreEqual(22, profile.UserId);
  }
}
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

No comments posted yet.
Your comment:
 (will show your gravatar)
 


Copyright © Aligned | Powered by: GeeksWithBlogs.net | Join free