Living in the Tech Avalanche Generation

A practitioner’s introspective on technology

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.

Share/Save/Bookmark

3 Comments so far

  1. Muhammad Mosa May 6th, 2009 11:49 pm

    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]

  2. Simon Segal May 7th, 2009 6:44 am

    Thanks Muhammad

    Always glad to see smiles.

    [Reply]

  3. Summary « Bogdan Brinzarea’s blog May 7th, 2009 9:54 pm

    [...] Simon Segal has a great post about mocking Entity Framework repositories with Moq. [...]

Leave a reply

Creative Commons Attribution-ShareAlike 2.5 Australia
Creative Commons Attribution-ShareAlike 2.5 Australia