24

In my method, I have my repository doing this:

bool isConditionMet = MyRepository.Any(x => x.Condition == true);

I am attempting to mock this using MOQ like so:

MyMockedRepository.Setup(x => x.Any(y => y.Condition == true)).Returns(true);

However, when the code executes, the repository call always returns false.

Is there a way to do this using MOQ?

** EDIT - Adding code per request **

I am using NHibernate so my Any method is in my base repository and implemented as such:

public virtual bool Any(Expression<Func<T, bool>> predicate)
{
    return Session.Query<T>().Cacheable().Any(predicate);
}
Brandon
  • 10,744
  • 18
  • 64
  • 97
  • Could you show more code for `MyRepository` is `Any()` the Linq extension method or part of `MyRepository`? – Mark Coleman Jul 26 '11 at 20:01
  • I added my Any method per request from my base repository. The mocked class is of `IMyRepository` which is implemented in `MyRepository`. – Brandon Jul 26 '11 at 20:11

1 Answers1

27

You need to match invocation arguments using It.Is, It.IsAny or It.IsRegex.

For example, to return true for any predicate, you could use:

MyMockedRepository
     .Setup(x => x.Any(It.IsAny<Expression<Func<T, bool>>>()))
     .Returns(true);

Or, you can match all expressions, but pass a delegate which will return a value depending on the expression itself:

Func<Expression<Func<T, bool>, bool> resultFunc = { ... }
MyMockedRepository
     .Setup(x => x.Any(It.IsAny<Expression<Func<T, bool>>>()))
     .Returns(resultFunc);
vgru
  • 49,838
  • 16
  • 120
  • 201
  • Please , can you tell me how resultFunc would look like ? – badr slaoui Dec 19 '15 at 21:00
  • @badrslaoui: depends on what/how you're testing. For example, you might know that the method you are testing will check if repository contains any values and simply return true. Or, you might mock a repo using a plain in-memory generic `List`, which means you can simply pass the expression parameter to list's `IQueryable.Any` and let it return `true` or `false`. Or, since the lambda can capture external variables, you can also keep a flag which indicates if you have any data or not, and then return the flag value. – vgru Dec 21 '15 at 12:10