最小起订量 - LINQ predicates的设置方法 [英] MOQ - LINQ Predicates in Setup Method

查看:200
本文介绍了最小起订量 - LINQ predicates的设置方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的方法,我有我的库这样做:

 布尔isConditionMet = MyRepository.Any(X => x.Condition ==真);
 

我试图嘲弄这种利用最小起订量像这样:

  MyMockedRepository.Setup(X => x.Any(Y => y.Condition ==真))返回(真)。
 

不过,code执行时,储备库调用始终返回false。

有没有办法做到这一点使用起订量?

**编辑 - 添加code每个请求**

我使用NHibernate的,所以我的任何方法在我的基础信息库,并实现为这样的:

 公共虚拟BOOL任何(出pression< Func键< T,布尔>> predicate)
{
    返回Session.Query< T>()可缓存()任何(predicate)。
}
 

解决方案

您需要使用匹配调用参数 It.Is It.IsAny It.IsRegex ​​

例如,返回任何的predicate,你可以使用:

  MyMockedRepository
     .Setup(X => x.Any(It.IsAny<防爆pression< Func键< T,布尔>>>()))
     .Returns(真正的);
 

或者,您可以匹配所有EX pressions,而是通过一个委托,将返回一个值根据前pression本身:

  Func键<防爆pression< Func键< T,布尔>中布尔> resultFunc = {...}
MyMockedRepository
     .Setup(X => x.Any(It.IsAny<防爆pression< Func键< T,布尔>>>()))
     .Returns(resultFunc);
 

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

解决方案

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

这篇关于最小起订量 - LINQ predicates的设置方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆