2017年3月15日 星期三

RhinoMocks stub out parameter

Ouch, pained my brain over this one for the last half hour or so, but finally found the solution.
I had a call similar to:
repository.Stub(x => x.TryGet(  
    Arg<Specification>.Matches(y => y.Something),
    out Arg<Customer>.Out(customerToReturn).Dummy))
.Return(true);
Because my first argument had a fairly large Matches call (it's simplified here), I refactored it to:
var specification = Arg<Specification>.Matches(y => y.Something);  
repository.Stub(x => x.TryGet(  
    specification, 
    out Arg<Customer>.Out(customerToReturn).Dummy))
.Return(true);
Ah, much more readable! Only, it didn't work. The exception I got was:
Use Arg<T> ONLY within a mock method call while recording. 2 arguments expected, 3 have been defined.
I could not for the life of me see where I was defining three arguments. I was looking at the second argument (the out argument) because that was the more exotic of the two.
I finally realized the exception message is actually rather correct. You have to use Arg inside the method you're stubbing. So you can't refactor like I did. I had to leave the call as it was:
repository.Stub(x => x.TryGet(  
    Arg<Specification>.Matches(y => y.Something),
    out Arg<Customer>.Out(customerToReturn).Dummy))
.Return(true);
I hope this saves you (and me!) some time in the future (as the few posts I found focus on the fact that the method has to be virtual, which doesn't help if you're stubbing an interface).

from : http://www.petermorlion.com/rhino_mocks_and_use_arg_t_only_within_a_mock_method_call_while_recording_exception/

沒有留言:

張貼留言