26

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.

davmos
  • 9,324
  • 4
  • 40
  • 43
Santhosh
  • 6,547
  • 15
  • 56
  • 63
  • Curious why you want to use Expectation, and not just go for AssertWasNotCalled? – Cousken Feb 27 '14 at 10:37
  • @Cousken AssertWasNotCalled() does not seem to work with BackToRecord() and Replay(), maybe that's the reason?? – danio Mar 07 '17 at 15:15

4 Answers4

36

Another option would be:

mockStore.Expect(x => x.Rollback()).Repeat.Never();
Pedro
  • 12,032
  • 4
  • 32
  • 45
8

Is this what are you looking for?

ITest test = MockRepository.GenerateMock<ITest>();
test.Expect(x => x.TestMethod()).AssertWasNotCalled(mi => {});
sll
  • 61,540
  • 22
  • 104
  • 156
3

Here is another option:

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

        //EXECUTION HERE 

        x.VerifyAllExpectations();
Morten
  • 3,778
  • 2
  • 25
  • 45
2

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.

MoMo
  • 8,149
  • 3
  • 35
  • 31