Pages

Thursday, November 27, 2014

Rhino mocks and number of executions

Yesterday I found annoying flaw in Rhino mocks. I expected that when you said Repeat.Twice() the expectation is that the method would be executed exactly 2 times and if no - expectation should be failed. But looks like that it saying "at least twice". (Despite the fact that there is as well Repeat.AtLeastOnce())

So here is my setup:
public class Foo
{
 public virtual void DoStuff()
 {
  Console.WriteLine("DoStuff");
 }
}

public class Bar
{
 public Foo foo { get; set; }

 public void CallFoo(int max)
 {
  for (int i = 0; i < max; i++)
  {
   foo.DoStuff();
  }
 }
}

And that test is not failing unfortunately. You can even replace Times(2) with anything else - just the number of executions should be less then the actual number - test still would be green. And you can replace it with Once() or AtLeastOnce() - no difference at all!

[Test]
public void MockTest()
{
 var mock = MockRepository.GenerateMock();

 mock.Expect(x => x.DoStuff())
  .Repeat.Times(2);

 var bar = new Bar();
 bar.foo = mock;

 bar.CallFoo(3);

 mock.VerifyAllExpectations();
}

And here is how you can write that test to fail. Finally, checking for exact number of calls!

[Test]
public void MockTest2()
{
 var mock = MockRepository.GenerateMock();
 
 var bar = new Bar();
 bar.foo = mock;

 bar.CallFoo(3);

 mock.AssertWasCalled(x => x.DoStuff(),
       y => y.Repeat.Times(2));
}

No comments:

Post a Comment