Rhino Mocks: Can I use Stub() when one of my parameters is Expression<Func<T1, T2>>?

孤街醉人 提交于 2019-12-05 07:36:46

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

I think the problem is related to how Expressions test equality. I just did a quick test in Snippet Compiler and my expressions never evaluated as the same:

    Expression<Func<int, string>> p = i => i.ToString();
    Expression<Func<int, string>> s = i => i.ToString();
    var b = p.Equals(s) || p == s;

(b was false for this test)

Probably in order for your test to work as is, you'd have to ignore the actual value of the second parameter (which may or may not be acceptable; If unacceptable I think you'll have to go the WhenCalled route).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!