如何使用Moq模拟函数中的谓词
本文关键字:谓词 函数 模拟 何使用 Moq | 更新日期: 2023-09-27 18:04:48
我想模拟Find方法,它期望使用Moq谓词:
public PurchaseOrder FindPurchaseOrderByOrderNumber(string purchaseOrderNumber)
{
return purchaseOrderRepository.Find(s => s.PurchaseOrderNumber == purchaseOrderNumber).FirstOrDefault();
}
My repository method
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把例外:系统。NotSupportedException:表达式引用了不属于模拟对象的方法:s =>.FirstOrDefault s.Find (It.IsAny ())
如何解决这个问题?
我找到了答案:)
我将测试更改如下,并删除了对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();
}