Living in the Tech Avalanche Generation

A practitioner’s introspective on technology

Entity Framework Repository Testing

Mark recently asked about testing the Repository / Fetching Strategy / Specification framework that I posted a while back. We can in fact bypass integration testing and by doing some state based testing on the Repository and utilise Specifications to filter the results.

[Test()]
public void mock_customers_only_where_in_germany()
{
    NorthwindEntities fake_entity_model = null;
    var mock_repo =
        new Mock<EntitiesRepository<Customer, NorthwindEntities>>
            (fake_entity_model);

    var germany_cust_spec =
        new Specification<Customer>(c => c.Country == “Germany”);

    var orders = new EntityCollection<Order>();
    orders.Add(new Order{Freight = 10M});
    orders.Add(new Order{Freight = 23M});

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

    var results = mock_repo.Object.AllToIList<ICustomerMakePrefered>();

    var cust = results.Where(germany_cust_spec.EvalFunc).First();

    cust.Makeprefered();

    Assert.That(cust.Orders.Sum(o => o.Freight) == 0);
    Assert.AreEqual(results.Count, 2);
    Assert.AreEqual(results.First().Country, “Germany”);
    Assert.AreEqual(mock_repo.Object
        .AllToIList<ICustomerMakePrefered>().Count, 2);
}

Where the Customer Entities MakePrefered method looks like this:

public void Makeprefered()
{
    foreach (var order in this.Orders)
    {
        order.Freight = 0M;
    }
}

So with the help of a bit of mocking we mimic the behaviour of the database, test our business logic and all with some degree of speed improvement.

Share/Save/Bookmark

4 Comments so far

  1. Alex James April 29th, 2009 1:42 pm

    Simon,

    Nice post, particularly timely for me. I’ve got a presentation to do on MVC, EF and Repositories.

    Cheers
    Alex

    [Reply]

  2. Simon Segal May 3rd, 2009 9:44 pm

    Alex

    Great. Look forward to seeing the presentation.

    Regards,

    Simon

    [Reply]

  3. [...] 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, [...]

  4. Interesting reads | Coded Style May 7th, 2009 2:26 pm

    [...] Segal has a interesting post on Entity Framework Repository testing. I found this particularly timely because of my upcoming TechEd talk about integrating MVC, EF and [...]

Leave a reply

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