我试图用Moq模拟我的存储库。我试图模拟出我的存储库上的所有查询方法。我已经成功地模拟出了返回所模拟类型的所有的方法。
的例子:
mockProductRepo.Setup(x => x.GetAll()).Returns(products.AsQueryable());
然而,我在模拟使用另一种方法的方法时遇到了问题。例如,我的"FilterBy"方法返回对我的"GetAll"方法的调用,其中包含一个Where子句,该子句接受一个表达式
示例:Repository Method
public virtual IQueryable<T> FilterBy(Expression<Func<T, bool>> expression)
{
return GetAll().Where(expression);
}
更重要的是,我希望在一个helper类中模拟存储库上的所有方法:
public static IRepository<Product> MockProductRepository(params Product[] products) {
var mockProductRepo = new Mock<IRepository<Product>>();
mockProductRepo.Setup(x => x.GetAll()).Returns(products.AsQueryable());
mockProductRepo.Setup(x => x.FilterBy(It.IsAny<Expression<Func<Product, bool>>>())).Returns(products.AsQueryable().Where(It.IsAny<Expression<Func<Product, bool>>>()));
return mockProductRepo.Object;
}
所以,而不是上面模拟的FilterBy方法,有没有一种方法来设置它调用另一个模拟的方法,而不是我在上面的例子中有它的方式?
我已经试过安装:
mockProductRepo.Setup(x => x.FilterBy(It.IsAny<Expression<Func<Product, bool>>>())).Returns(mockProductRepo.Object.GetAll().Where(It.IsAny<Expression<Func<Product, bool>>>()));
总是错误提示"Value不能为null"。参数:谓语"。从我对堆栈跟踪的理解来看,它在抱怨,因为我没有传递"Where"谓词。我不确定如何在设置中表示传递到过滤器中使用的FilterBy方法的表达式。
我自己想的。
mockProductRepo.Setup(x => x.FilterBy(It.IsAny<Expression<Func<Product, bool>>>())).Returns((Expression<Func<Product,bool>> filter) => mockProductRepo.Object.GetAll().Where(filter));