Rhino Mocks:当我的参数之一是 Expression<Func<T1, T2>> 时,我可以使用 Stub() 吗? [英] Rhino Mocks: Can I use Stub() when one of my parameters is Expression&lt;Func&lt;T1, T2&gt;&gt;?

查看:22
本文介绍了Rhino Mocks:当我的参数之一是 Expression<Func<T1, T2>> 时,我可以使用 Stub() 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个界面上有一个方法,看起来像这样,我想用 Rhino Mocks 存根它:

I have a method on an interface that looks like this and I want to stub it with Rhino Mocks:

TValue GetPropertyOfExistingObject<TValue>(long id, Expression<Func<T, TValue>> propertyExpression);

我的存根代码如下所示:

My code that does the stubbing looks like this:

var service = MockRepository.GenerateStub<IQuoteService>();
service.Stub(s => s.GetPropertyOfExistingObject(1, q => q.QuoteNumber)).Return(1234);

请注意,该方法中的参数之一是 Expression>,并且此存根未返回指定值.我知道我可以通过使用 WhenCalled() 来做到这一点,但我想知道 Stub() 是否应该使用表达式参数,或者我是否只是做错了什么.

Notice that one of the parameters in that method is an Expression<Func<T1, T2>>, and this stub is not returning the specified value. I know I can do this by using WhenCalled() but I was wondering if Stub() should work with expression parameters or if I'm just doing something wrong.

推荐答案

您可以创建一个方法来评估两个表达式之间的相等性:

You can create a method that evaluates the equality between two expressions:

public class ExpressionMatcher
{
    public static Expression<Action<T>> Matches<T>(Expression<Action<T>> action)
    {
        var methodName = ((MethodCallExpression) action.Body).Method.Name;
        return Arg<Expression<Action<T>>>.Matches(a => ((MethodCallExpression)a.Body).Method.Name.Equals(methodName));
    }
}

然后更改存根语句以将表达式包装在对表达式匹配器的调用中:

Then change your stub statement to wrap the expression in a call to the expression matcher:

service.Stub(s => s.GetPropertyOfExistingObject(Arg<int>.Is.Equal(1), ExpressionMatcher.Matches<Quote>(q => q.QuoteNumber))).Return(1234);

这篇关于Rhino Mocks:当我的参数之一是 Expression<Func<T1, T2>> 时,我可以使用 Stub() 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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