Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MOQ - LINQ Predicates in Setup Method

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);
}
like image 633
Brandon Avatar asked Jul 26 '11 19:07

Brandon


1 Answers

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);
like image 79
Groo Avatar answered Nov 20 '22 17:11

Groo