我正在尝试为测试目的设置模拟DbSet。我在这里使用了教程,http://www.loganfranken.com/blog/517/mocking-dbset-queries-in-ef6/并略微修改了它,所以每次调用GetEnumerator都会返回一个新的枚举器(我遇到的另一个问题)。但是,我很难将项目添加到DbSet。如何将项目添加到模拟DbSet(使用Moq)
输出是preCount = 3 postCount = 3.但是,我期望它是预计数= 3 postCount = 4.任何帮助非常感谢。
static void Main(string[] args)
{
Debug.WriteLine("hello debug");
List<string> stringList = new List<string>
{
"a", "b", "c"
};
DbSet<string> myDbSet = GetQueryableMockDbSet(stringList);
int preCount = myDbSet.Count();
myDbSet.Add("d");
int postCount = myDbSet.Count();
Debug.WriteLine("preCount = " + preCount + " postCount = " + postCount);
}
private 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());
return dbSet.Object;
}
很不错的方法来封装创建dbSet。 你有没有更新过这个来支持异步查询? –
至少目前与.net核心1.0,这将回答异步问题:[如何使用实体框架核心模拟异步存储库](https://stackoverflow.com/questions/40476233/how-to-mock -an-async-repository-with-entity-framework-core) –