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

I have an interface method that looks like this, and I want to drown it out with Rhino Mocks:

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

My code that does stubbing looks like this:

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

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

+6
rhino-mocks
source share
2 answers

You can create a method that evaluates 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 modify your stub statement to wrap the expression in the call with the expression:

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

I think the problem is with the way expressions express equality. I just did a quick test in the Snippet compiler, and my expressions were 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 wrong for this test)

You may have to ignore the actual value of the second parameter (which may or may not be acceptable; if it is unacceptable, I think you will have to go along the WhenCalled route) in order for your test to work as it is.

+2
source share

All Articles