Michael
Michael

Reputation: 13

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!

Upvotes: 1

Views: 2877

Answers (2)

Amittai Shapira
Amittai Shapira

Reputation: 3827

First of all - try to use Rhino Mocks 3.5 syntax, it's much easier
Secondly you should get into Replay state after you've set your expectations and starting the actual testas follows:

using (mocks.Playback())   {   _controller.Index()   }

3.5 Syntax should be something like this:

    MockRepository mocks = new MockRepository();
    IServiceCalls serviceCallsMock = MockRepository.GenerateMock<IServiceCalls>();
    _controller.ServiceCalls = serviceCallsMock;
    serviceCallsMock.Expect(x => x.GetX(2)).Return(new List<X> { new X{ Id = 1 } });
    _controller.Index();
    serviceCallsMock.VerifyAllExpectations()

Upvotes: 0

WaltiD
WaltiD

Reputation: 1952

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.

Upvotes: 1

Related Questions