-
-
Save Alejoho/893e7aaa72a8cb93ea1dcdb849633d21 to your computer and use it in GitHub Desktop.
Db Context Mockup using Moq
This file contains hidden or 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
| using Microsoft.EntityFrameworkCore; | |
| using Moq; | |
| using System.Collections.Generic; | |
| using System.Linq; | |
| namespace NETCore3WebApp.Test.Business { | |
| public static class DbContextMock { | |
| public static DbSet <T> GetQueryableMockDbSet <T> (List <T> sourceList) where T: class | |
| { | |
| var queryable = sourceList.AsQueryable(); | |
| var dbSet = new Mock<DbSet<T>>(); | |
| dbSet.As<IQueryable<T>>().Setup(m => m.Provider).Returns(queryable.Provider); | |
| dbSet.As<IQueryable<T>>().Setup(m => m.Expression).Returns(queryable.Expression); | |
| dbSet.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(queryable.ElementType); | |
| dbSet.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(() => queryable.GetEnumerator()); | |
| dbSet.Setup(d => d.Add(It.IsAny<T>())).Callback<T>((s) => sourceList.Add(s)); | |
| return dbSet.Object; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment