Brian Low
Brian Low

Reputation: 11811

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.

Upvotes: 5

Views: 1787

Answers (2)

Gene C
Gene C

Reputation: 2030

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

Upvotes: 5

Amittai Shapira
Amittai Shapira

Reputation: 3827

I've reread your question and it seems that you want some method to seperate between the calls to the mock during the Arrange stage, and the calls to the mock during the Act stage. I don't know of any built-in support for it, but what you can do is pass a callback by using WhenCalled. In your case the code would be something like:

// Arrange
var engineMock = MockRepository.GenerateStub<IEngine>();
var car = new Car(engineMock);
int openThrotlleCount = 0;
engineMock.Expect(x => x.OpenThrottle(arg)).WhenCalled(invocation => openThrotlleCount++);
car.DriveToGroceryStore(); // this will call engine.OpenThrottle
var openThrottleCountBeforeAct = openThrotlleCount;

// Act
car.DriveHome();

// Assert
Assert.Greater(openThrotlleCount, openThrottleCountBeforeAct);

Hope it helps...

Upvotes: 2

Related Questions