Entity Framework Repository Testing : addendum
I recently posted on how to do state based testing with Repositories and the Entity Framework but failed to mention that if you are using a mocking framework like MOQ, that enforces that Mocked behaviours are required to be virtual, then that’s fine, but it’s bad practice (IMO) to leave the after effect of that lying around in the release versions of your code. Here’s an example:
var mock_repo =
new Mock<EntitiesRepository<Customer, NorthwindEntities>>
(fake_entity_model);
mock_repo
.Expect(repo => repo.AllToIList<ICustomerMakePrefered>())
.Returns(new List<Customer>()
{
new Customer()
{
CustomerID = “ALFKI”,
Country = “Germany”,
Orders = orders
},
new Customer()
{
CustomerID = “SIMSE”, Country = “Australia”
}
});
When using MOQ, this requires the Repository to have it’s AllToIList method marked with the virtual access modifier but that isn’t necessarily my intent. One way of approaching it is conditional compilation.
#if(DEBUG) public virtual IList<TEntity> AllToIList() #else public IList<TEntity> AllToIList() #endif { var entity_set_name = FindEntitySetName(); var qry = _ctx.CreateQuery<TEntity>(“[" + entity_set_name + "]“); return qry.ToList(); }
So conditional complication directives help clean up our code and make sure that any requirement in mocking is not overriding our object design intentions.
3 Comments so far
Leave a reply









Segal! you made me smile. I am happy that I am subscribed to your feeds :o)
I must try that later today to clean up my code. Code refactoring point
[Reply]
Thanks Muhammad
Always glad to see smiles.
[Reply]
[...] Simon Segal has a great post about mocking Entity Framework repositories with Moq. [...]