Wednesday, September 22, 2010

Rhino Mocks and constraints on Object Parameters

The Is.Matching Rhino Mocks constraint is really nice way to setup expectation constraints on object parameters.

Is.Matching expects a predicate delegate which means the constraint can be very flexible - which is needed since the expectations on the object can be complex due to the possibility of several properties that require certain values.

Below is an example of setting up the expectation using an annoymous delegate. In this test we are expecting the Query object that is passed in the call to the GetCustomer method having an Id of 10 and BusinessGroup of "Finance". The declarations of request and response has been omitted to keep the code snippet concise.

MockRepository repo = new MockRepository;
IProvider mockProvider = repo.DynamicMock();
mockProvider.Expect( x => x.GetCustomer(request)).Constraints(Is.Matching(delegate(Query qry){ return (qry.Id == 10 && qry.BusinessGroup == "Finance"); })).Return(response);


As an aside, using the DynamicMock factory method rather than StrictMock means the call to the mockProvider in the code under test with the parameter expectations incorrect won't throw an exception, where using StrickMock will. However, using DynamicMock with the incorrect parameter passed in, mockProvider.GetCustomer will return null - so unless you have a check in your code under test for a null being return then an exception will be thrown anyway. So with this in mind, personally I believe that the StrictMock factory should be used when there is a Return object required.

No comments:

Post a Comment