Blog Post

EF - Setting up IQueryable DbSet for unit test

Saturday, May 14, 2016 1:43 PM

Today I have needed to write unit test for Entity Framework data set.I  have done a bingle the solution by quick search, and I have not found nice way to do that in my time that I have set for myself. 

I want to share the solution I have come up with that works really nicely.

Solution example

Lets set up our context used under test 

public class DemoContext : DbContext, IDemoContext
{
public IDbSet<Audit> Audit { get; set; }

 

My testing solution is using Moq for setting up objects (mocking)

For this db set I have created generic helper method

private Mock<DbSet<T>> SetupDbSet<T>(IQueryable<T> data) where T : class
{
var mockSet = new Mock<DbSet<T>>();
mockSet.As<IQueryable<T>>().Setup(m => m.Provider).Returns(data.Provider);
mockSet.As<IQueryable<T>>().Setup(m => m.Expression).Returns(data.Expression);
mockSet.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(data.ElementType);
mockSet.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(() => data.GetEnumerator());
return mockSet;
}

 

 private void SetupAudit(IQueryable<Audit> data)
{
var mockSet = SetupDbSet(data);
_demoContext.Setup(x => x.Audit).Returns(mockSet.Object);
}

 

Now we will use following line and provide data for the dbset we want to have mocked.

SetupAudit(new List<Audit>() {}.AsQueryable());

 

 

Blog
Products
Error pages
Links and tools