Skip to content

Moq extension methods for mocking DbSet with LINQ queries

License

Notifications You must be signed in to change notification settings

luetm/MockDbSet

 
 

Repository files navigation

MockDbSet

Moq extension methods for mocking DbSet with LINQ queries

Mocking a DbSet is easy, but if you try to use the mock as-is with your LINQ queries, you will discover that it needs some massaging to work as expected; especially when you use it with async queries. The secret is to setup an implementation of IQueryable for the DbSet and to wire it to our predefined data; making use of the LINQ to Objects provider that works with List<T>.

This lib performs all that plumbing for you, and contains two extension methods that makes mocking your DbSet properties a breeze:

  • ReturnsDbSet
  • ReturnsAsyncDbSet

Example usage

var expenses = new List<Expense> { new Expense { Id = 1 } };
var mockContext = new Mock<TestContext>();
mockContext.Setup(p => p.Set<Expense>()).ReturnsDbSet(expenses);

How do I get a hold of it?

The lib is available as a NuGet package:

PM> Install-Package MockDbSetExtensions

Credits

The code in this repo is heavily inspired by (as in mostly copied from) other resources:

About

Moq extension methods for mocking DbSet with LINQ queries

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • C# 99.1%
  • Batchfile 0.9%