26
votes

Using Rhino Mocks, how do I ensure that a method is not called while setting up the Expectations on the mock object.

In my example, I am testing the Commit method and I need to ensure that the Rollback method is not called while doing the commit. (this is because i have logic in the commit method that will automatically rollback if commit fails)

Here's how the code looks like..

[Test]
public void TestCommit_DoesNotRollback() 
{
    //Arrange
    var mockStore = MockRepository.GenerateMock<IStore>();
    mockStore.Expect(x => x.Commit());
    //here i want to set an expectation that x.Rollback() should not be called.

    //Act
    subject.Commit();

    //Assert
    mockStore.VerifyAllExpectation();
}

Of course, I can do this at Assert phase like this:

mockStore.AssertWasNotCalled(x => x.Rollback());

But i would like to set this as an Expectation in the first place.

4
Curious why you want to use Expectation, and not just go for AssertWasNotCalled?Cousken
@Cousken AssertWasNotCalled() does not seem to work with BackToRecord() and Replay(), maybe that's the reason??danio

4 Answers

36
votes

Another option would be:

mockStore.Expect(x => x.Rollback()).Repeat.Never();
8
votes

Is this what are you looking for?

ITest test = MockRepository.GenerateMock<ITest>();
test.Expect(x => x.TestMethod()).AssertWasNotCalled(mi => {});
3
votes

Here is another option:

        mockStore.Stub(x => x.DoThis()).Repeat.Times(0);

        //EXECUTION HERE 

        x.VerifyAllExpectations();
2
votes

For this case I created an extension method to better show my intent

public static IMethodOptions<RhinoMocksExtensions.VoidType> ExpectNever<T>(this T mock, Action<T> action) where T : class
{
    return mock.Expect(action).IgnoreArguments().Repeat.Never();
}

Note the IgnoreArguments() call. I'm assuming that you don't want the method to be called ever...no matter what the parameter value(s) are.