【问题标题】:How to Mock a Predicate in a Function using Moq如何使用 Moq 在函数中模拟谓词
【发布时间】:2011-10-22 22:33:32
【问题描述】:

我想模拟 Find 方法,它需要使用 Moq 的谓词:

public PurchaseOrder FindPurchaseOrderByOrderNumber(string purchaseOrderNumber)
    {
        return purchaseOrderRepository.Find(s => s.PurchaseOrderNumber ==    purchaseOrderNumber).FirstOrDefault();
    }

我的存储库方法

IList<TEntity> Find(Func<TEntity, bool> where);

我使用了以下测试方法

[TestMethod]
  public void CanGetPurchaseOrderByPurchaseOrderNumber()
 {

      _purchaseOrderMockRepository.Setup(s => s.Find(It.IsAny<Func<PurchaseOrder, bool>>()).FirstOrDefault())
          .Returns((Func<PurchaseOrder, bool> expr) => FakeFactory.GetPurchaseOrder());

      _purchaseOrderService.FindPurchaseOrderByOrderNumber("1111");


 }

它给了我以下错误:

ServicesTest.PurchaseOrderServiceTest.CanGetPurchaseOrderByPurchaseOrderNumber 抛出异常: System.NotSupportedException:表达式引用了不属于模拟对象的方法:s => s.Find(It.IsAny()).FirstOrDefault

我该如何解决这个问题?

【问题讨论】:

    标签: c# moq


    【解决方案1】:

    我找到了答案:)

    我将测试更改如下,并删除了对 FirstOrDefault 的调用:

    [TestMethod]
      public void CanGetPurchaseOrderByPurchaseOrderNumber()
     {
    
          _purchaseOrderMockRepository.Setup(s => s.Find(It.IsAny<Func<PurchaseOrder, bool>>()))
              .Returns((Func<PurchaseOrder, bool> expr) => new List<PurchaseOrder>() {FakeFactory.GetPurchaseOrder()});
    
          _purchaseOrderService.FindPurchaseOrderByOrderNumber("1111");
    
          _purchaseOrderMockRepository.VerifyAll();
    
    
     }
    

    【讨论】:

    • 游戏有点晚了,但这对我帮助很大。谢谢!
    猜你喜欢
    • 2016-12-15
    • 2012-02-18
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    • 2011-02-27
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    相关资源
    最近更新 更多