9

So: I'd like to count method calls in Rhino Mocks with something more specific than Any(), Once() or AtLeastOnce(). Is there any mechanism for doing this?

Tim Barrass
  • 4,813
  • 2
  • 29
  • 55
  • A solution to this **is** along similar lines to [other questions][1], so do vote-to-close if it's too close: am posting this specific question because nothing popped out at me when I searched SO originally. [1]: http://stackoverflow.com/questions/1349364/rhino-mocks-set-a-property-if-a-method-is-called – Tim Barrass Jul 27 '11 at 11:21
  • Now I know what I'm looking for, variants at: http://stackoverflow.com/questions/729267/rhino-mocks-assertwascalled-multiple-times-on-property-getter-using-aaa, http://stackoverflow.com/questions/466520/what-is-rhino-mocks-repeat which, weirdly, didn't seem to pop up in searches for this question. – Tim Barrass Jul 27 '11 at 13:44

1 Answers1

11

The trick is to use Repeat.Times(n), where n is the number of times.

Suprisingly the below test will pass, even if the method is called more often than expected:

[Test]
public void expect_repeat_n_times_does_not_work_when_actual_greater_than_expected() {
  const Int32 ActualTimesToCall = 6;
  const Int32 ExpectedTimesToCall = 4;

  var mock = MockRepository.GenerateMock<IExample>();
  mock.Expect(example => example.ExampleMethod()).Repeat.Times(ExpectedTimesToCall);

  for (var i = 0; i < ActualTimesToCall; i++) {
      mock.ExampleMethod();
  }

  // [?] This one passes
  mock.VerifyAllExpectations();
}

To work around this use the below method:

[Test]
public void aaa_repeat_n_times_does_work_when_actual_greater_than_expected() {
  const Int32 ActualTimesToCall = 6;
  const Int32 ExpectedTimesToCall = 4;

  var mock = MockRepository.GenerateMock<IExample>();

  for (var i = 0; i < ActualTimesToCall; i++) {
      mock.ExampleMethod();
  }

  // This one fails (as expected)
  mock.AssertWasCalled(
      example => example.ExampleMethod(),
      options => options.Repeat.Times(ExpectedTimesToCall)
  );
}

Source: http://benbiddington.wordpress.com/2009/06/23/rhinomocks-repeat-times/ (look there for an explanation)

EDIT: only edited to summarise at the start, thanks for the useful reply.

Tim Barrass
  • 4,813
  • 2
  • 29
  • 55
Onots
  • 2,118
  • 21
  • 28