tags:

views:

33

answers:

1

In the code below, if I understand it correctly, I am stubbing the Speed property and setting it to 0 which should call the Stop method, but when I run the test, it is saying that it expected Stop to be called, but it was not called. Here is the code:

 public class Car
 {
    public virtual int Speed { get; set; }

    public virtual bool Stopped()
    {
        if (Speed > 0)
            return false;

        Stop();
        return true;
    }

    public virtual void Stop()
    {

    }
}

[TestFixture]
public class CarTests
{
    [Test]
    public void WhenSpeedIsZeroCarShouldBeStopped()
    {
        var carMock = MockRepository.GenerateMock<Car>();
        carMock.Stub(x => x.Speed).Return(0);
        carMock.Expect(x => x.Stop());

        carMock.VerifyAllExpectations();
    }
}

The actual error I am getting is:

Rhino.Mocks.Exceptions.ExpectationViolationException: Car.Stop(); Expected #1, Actual #0.
   at Rhino.Mocks.Impl.ReplayMockState.Verify()
   at Rhino.Mocks.MockRepository.Verify(Object obj)
   at Rhino.Mocks.RhinoMocksExtensions.VerifyAllExpectations(Object mockObject)
   at MockTutorial.CarTests.WhenSpeedIsZeroCarShouldBeStopped() in C:\Programming\Test\MockTutorial\MockTutorial\DirectoryInfoSample.cs:line 94
+1  A: 

You're not calling Stopped() - so what would be either asking for the Speed property or calling Stop()?.

Jon Skeet
Ah that would make sense, because that calls Stop(), duh.
Xaisoft
How can I fake it to call Stopped?
Xaisoft
@Xaisoft: Surely you don't *want* to fake the call to Stopped. You want to *actually* call Stopped, and check that you get the right result.
Jon Skeet
In fact, I'm not sure exactly how you'd do this in Rhino Mocks, because you want a *partial* mock - and I've not done those, personally. I typically mock out *dependencies* rather than virtual methods in the class I'm testing. I'm not at all sure that this is a good place to use mocking, to be honest. And I'm also unsure that a method call Stopped() should be actually *calling* Stop() - shouldn't it be checking whether it already *is* stopped, rather than actively stopping it? If the speed is zero, isn't it already stopped?
Jon Skeet
I agree with everything you said. I was actually just messing around with Rhino Mocks. I know it is poorly designed code. Thanks for the feedback.
Xaisoft