如何使用Moq模拟函数中的谓词

时间:2011-08-09 05:43:06

标签: c# moq

我想模拟使用Moq期望谓词的Find方法:

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:Expression引用不属于模拟对象的方法:s =&gt;   s.Find(It.IsAny())。FirstOrDefault

如何解决此问题?

1 个答案:

答案 0 :(得分:15)

我找到了答案:)

我按如下方式更改了测试并删除了对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();


 }