Created
November 26, 2020 21:04
-
-
Save eduardosilva/746b15df06f70fe552b2ae01f42cbcfb to your computer and use it in GitHub Desktop.
Moq with Entity Framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class QueryableExtensions | |
{ | |
public static Mock<DbSet<T>> ToMockDbSet<T>(this IQueryable<T> source) | |
where T : class | |
{ | |
var mock = new Mock<DbSet<T>>(); | |
mock.As<IQueryable<T>>() | |
.Setup(x => x.Provider) | |
.Returns(source.Provider); | |
mock.As<IQueryable<T>>() | |
.Setup(x => x.Expression) | |
.Returns(source.Expression); | |
mock.As<IQueryable<T>>() | |
.Setup(x => x.ElementType) | |
.Returns(source.ElementType); | |
mock.As<IQueryable<T>>() | |
.Setup(x => x.GetEnumerator()) | |
.Returns(source.GetEnumerator()); | |
mock.Setup(x => x.Attach(It.IsAny<T>())).Returns((T x) => x); | |
mock.Setup(c => c.Include(It.IsAny<string>())).Returns(mock.Object); | |
return mock; | |
} | |
} | |
// using | |
var dbSet = new Cars[]{ new Car{ Id = 1}, new Car{ Id = 2}}.AsQueryable().ToMockDbSet(); | |
var dataContext = new Mock<DataContext>(); | |
dataContext.Setup(c => c.Cars).Returns(dbSet.Object); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment