Wednesday, April 24, 2013

Unit testing the EF DataContext using Moq and FakeDbSet

I came across a very sweet way of testing EF DataContexts: http://www.nogginbox.co.uk/blog/mocking-entity-framework-data-context . This guy figured it out.

What he does is:
- Change all DbSet<...> in your EF DataContext to IDbSet<...>
- Extract an interface
- Get NuGet package Moq : https://www.nuget.org/packages/moq
- Get NuGet package FakeDbSet : http://nuget.org/packages/FakeDbSet/

Setup a test datacontext with some data like so:

// Create mock unit of work
var mockDataContext = new Mock<IDataContext>();
var mockItemList= new InMemoryDbSet<item>(clearDownExistingData: true)
{
new item(FakeDepartureDate1, "drp1", "drp3", 1), 
new item(FakeDepartureDate1, "drp1", "drp3", 2), 
new item(FakeDepartureDate1, "drp1", "drp3", 2), 
new item(FakeDepartureDate2, "drp2", "drp3", 4), 
new item(FakeDepartureDate2, "drp2", "drp4", 5), 
new item(FakeDepartureDate2, "drp2", "drp4", 5)
};
mockDataContext.Setup(m => m.itemList).Returns(mockItemList);

And presto - you can start testing against your fake data. I used it to prove my query worked correctly.

EntityFramework testing will be done like so from now on by me!

But - don't take my word for it - check out the guy who figured it out before me:


No comments:

Post a Comment