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.
4 comments








