Skip to content

Instantly share code, notes, and snippets.

@LexVocoder
Created February 12, 2018 22:36
Show Gist options
  • Save LexVocoder/d53b4d5aed337c4b5946974ccb2e9994 to your computer and use it in GitHub Desktop.
Save LexVocoder/d53b4d5aed337c4b5946974ccb2e9994 to your computer and use it in GitHub Desktop.
MockDbSet for mocking EF DbContext
using Microsoft.EntityFrameworkCore;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System.Collections.Generic;
using System.Linq;
...
private static Mock<DbSet<T>> MockDbSet<T>(IEnumerable<T> ls) where T : class
{
var data = ls.AsQueryable();
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment