使用Moq模拟存储库的问题

时间:2011-04-13 11:45:18

标签: c#-4.0 moq repository-pattern

我试图用Moq模拟我的存储库。我试图模拟我的存储库上的所有查询方法。我已经成功地模拟了返回所有类型的方法。

示例:

mockProductRepo.Setup(x => x.GetAll()).Returns(products.AsQueryable());

但是,我遇到了一个模拟使用其他方法的方法的问题。例如,我的“FilterBy”方法返回对我的“GetAll”方法的调用,其中Where子句带有表达式

示例:存储库方法

public virtual IQueryable<T> FilterBy(Expression<Func<T, bool>> expression)
{
   return GetAll().Where(expression);
}

踢球者是我希望在帮助程序类中模拟存储库中的所有方法:

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方法的表达式在过滤器Where中使用。

1 个答案:

答案 0 :(得分:7)

我自己想到了。

mockProductRepo.Setup(x => x.FilterBy(It.IsAny<Expression<Func<Product, bool>>>())).Returns((Expression<Func<Product,bool>> filter) => mockProductRepo.Object.GetAll().Where(filter));