Search code examples
unit-testingmockingrhino-mocks

RhinoMocks: Clear or reset AssertWasCalled()


How can I verify a mock is called in the "act" portion of my test ignoring any calls to the mock in the "arrange" portion of the test.

[Test]
public void ShouldOpenThrottleWhenDrivingHome()
{
    var engineMock = MockRepository.GenerateStub<IEngine>();
    var car = new Car(engineMock);
    car.DriveToGroceryStore(); // this will call engine.OpenThrottle

    car.DriveHome();

    engine.AssertWasCalled(e => e.OpenThrottle());
}

I'd prefer not to try an inject a fresh mock or rely on .Repeat() because the test then has to know how many times the method is called in the setup.


Solution

  • In these situations I use a mock instead of a stub and combination of Expect and VerifyAllExpectations:

    //Arrange
    var engineMock = MockRepository.GenerateMock<IEngine>();
    var car = new Car(engineMock);
    car.DriveToGroceryStore(); // this will call engine.OpenThrottle
    
    engineMock.Expect(e => e.OpenThrottle());
    
    //Act
    car.DriveHome();
    
    //Assert
    engineMock.VerifyAllExpectations();
    

    In this case the expectation is placed on the method after the arranging is complete. Sometimes I think of this as its own testing style: Arrange, Expect, Act, Assert