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);
}
}