Using Moq to Mock Entity Framework DBSet objects
💻 coding

Using Moq to Mock Entity Framework DBSet objects

1 min read 200 words
1 min read
ShareWhatsAppPost on X
  • 1Unit testing with Entity Framework 6 can be challenging due to its limitations in mocking DbSet objects.
  • 2Moq can be used to create mock DbSet objects from IEnumerable collections for testing purposes.
  • 3The provided extension method allows for easy setup of mock DbSet properties in your tests.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"Unit testing with Entity Framework 6 can be challenging due to its limitations in mocking DbSet objects."

Using Moq to Mock Entity Framework DBSet objects

Unit testing in .NET is pretty nice when your dependency injection/IoC is set up well, but Entity Framework 6 isn’t the nicest framework for mocking and testing. If you’re using ASP.NET MVC 5, you may have run into this scenario.

Problem: You want to use or mock a DbSet

So you have an IEnumerable (list, array, etc) that you want to use on your tests, but your DbContext only has DbSets. Unfortunately, the DbSet constructor is protected, so you can’t just ‘new’ one up. The solution is our friend Moq.

Solution

This handy IEnumerable extension will give you back a DBSet with your IEnumerable in the data. Now you can mock out your DbContext properties or result sets however you wish! You probably want to leave callBase as true to the base implementation is called when you haven’t set up certain properties, but if you’re having problems, maybe try setting callBase to false.

public static class TestingExtensions
{
 private static Mock<DbSet<T>> AsMockDbSet<T>(IEnumerable<T> data, bool callBase = true) where T : class
 {
 var mockSet = new Mock<DbSet<T>>();
 var queryable = data.AsQueryable();

 mockSet.As<IQueryable<T>>().Setup(m => m.Provider).Returns(queryable.Provider);
 mockSet.As<IQueryable<T>>().Setup(m => m.Expression).Returns(queryable.Expression);
 mockSet.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(queryable.ElementType);
 mockSet.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(queryable.GetEnumerator());

 mockSet.CallBase = callBase;

 return mockSet;
 }
}

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 23 March 2019 · 1 min read · 200 words

Part of AskGif Blog · coding

You might also like

Using Moq to Mock Entity Framework DBSet objects | AskGif Blog