Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Mock a Predicate in a Function using Moq

Tags:

c#

moq

I want to mock Find method which expects a predicate using Moq:

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

My repository method

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

I used following test method

[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");


 }

It gives me the following error:

ServicesTest.PurchaseOrderServiceTest.CanGetPurchaseOrderByPurchaseOrderNumber threw exception: System.NotSupportedException: Expression references a method that does not belong to the mocked object: s => s.Find(It.IsAny()).FirstOrDefault

How do I resolve this?

like image 745
marvelTracker Avatar asked Aug 09 '11 05:08

marvelTracker


1 Answers

I found the answer :)

I changed the test as follows and removed the call to 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();


 }
like image 86
marvelTracker Avatar answered Oct 27 '22 00:10

marvelTracker