Search code examples
c#.netrhino-mocks

Rhino Mocks: ExpectationViolationException although calls are in expected order


I'm having a problem with Rhino Mocks. My Test method looks like this:

        MockRepository mocks = new MockRepository();
        IServiceCalls serviceCallsMock = mocks.StrictMock<IServiceCalls>();
        _controller.ServiceCalls = serviceCallsMock;

        using (mocks.Record())
        {
            serviceCallsMock.GetX(2);
            LastCall.Return(new List<X> { new X{ Id = 1 } });

            serviceCallsMock.SetX(new X{ Id = 2 });
        }

        _controller.Index();

        mocks.Verify(serviceCallsMock);

The calls in the _controller.Index() method are in the right order and with the right parameters. But I get the following failure:

Rhino.Mocks.Exceptions.ExpectationViolationException
 IServiceCalls.SetX(Namespace.X); Expected #0, Actual #1.
 IServiceCalls.SetX(Namespace.X); Expected #1, Actual #0.

Does anyone know, what I'm doing wrong?

Thanks in advance!


Solution

  • The problem is in this line:

    serviceCallsMock.SetX(new X{ Id = 2 });
    

    The mock is now expecting to be called with exactly this instance of X.
    You should probably use Argument Constraints. Try something like

    Is.Matching<X>(delegate(X) x 
      { return x.Id == 2; } )
    

    See Rhino Mocks Quick Reference for more details.