【问题标题】:Problems mocking out Repository with Moq使用 Moq 模拟存储库的问题
【发布时间】:2011-04-13 11:45:17
【问题描述】:

我正在尝试使用 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>>>()));

而且总是报错“值不能为空。参数:谓词”。根据我对堆栈跟踪的了解,它在抱怨,因为我没有传递“Where”谓词。我不确定如何在设置中表示传递给 FilterBy 方法的表达式,以便在过滤器 Where 中使用。

【问题讨论】:

    标签: c#-4.0 moq repository-pattern


    【解决方案1】:

    我自己想出来的。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-28
      • 2011-05-27
      • 2011-05-27
      • 1970-01-01
      • 1970-01-01
      • 2015-09-08
      相关资源
      最近更新 更多