开发者

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 NHi开发者_StackOverflow中文版bernate 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);
}


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜