Convert a test to Rhino Mocks 3.5 and the number of constraints

Wednesday, 01 October 2008

Posted by Sébastien Lachance with Comments (0)

I decided to convert a test to Rhino Mocks 3.5 to "enhance readability". This test was using constraints to make sure that properties of a supplied object was changed during the execution of the tested method.

Original Code :

var mockery = new MockRepository();
var mockedRequestRepository = mockery.DynamicMock<IRequestRepository>();
var sut = new RequestService(mockedPreviewRequestRepository, null);

Expect.Call(mockedRequestRepository.GetByID(1)).Return(new Request { ID = 1 });
mockedRequestRepository.Update(null);
LastCall.Constraints(Property.Value("RequestState", RequestState.BeingProcessed));

mockery.ReplayAll();

sut.MarkAsBeingProcessed(1);

mockery.VerifyAll();

 

Converted Code (Rhino Mocks 3.5) :

var requestRepository = MockRepository.GenerateMock<IPreviewRequestRepository>();

var sut = new RequestService(requestRepository, null);

requestRepository.Expect(rr => rr.GetByID(1)).Return(new Request {ID = 1});
requestRepository.Expect(rr => rr.Update(null)).IgnoreArguments().Constraints(
    Property.Value("RequestState", RequestState.BeingProcessed), Property.Value("ID", 1));

sut.MarkAsBeingProcessed(1);

requestRepository.VerifyAllExpectations();

 

However, on the converted test, I got this nasty exception :

System.InvalidOperationException: The number of constraints is not the same as the number of the method's parameters!

After playing around with different combinations of constraints I found out that you can supply a predicate to the Is.Matching constraint. So I ended up modifying my constraint a little.

requestRepository.Expect(rr => rr.Update(null)).IgnoreArguments().Constraints(
         Rhino.Mocks.Constraints.Is.Matching(
             (IRequest request) => request.ID == 1 && request.RequestState == RequestState.BeingProcessed));

 

Et voila! Everything works fine. However, I would like to hear how you got to get rid of this message if there is another way.

 




blog comments powered by Disqus