views:

55

answers:

1

Using NUnit and Moq, I am trying to wrap some tests around legacy code before I do too much more refactoring. I need to test that a method keeps looping until told to stop. Here is my idea how to do it:

[TestCase]
public void KeepsCallingDoSomethingUntilShouldIKeepGoingIsFalse()
{
   var dal = new Mock<IDataAccessLayer>();
   var sut = new MyService(dal.Object);
   int numberOfTimesToReturnTrue = 5;
   dal.Setup(x => x.ShouldIKeepGoing())
       .Callback(() => numberOfTimesToReturnTrue--)
       .Returns(() => numberOfTimesToReturnTrue >= 0);

   sut.Blah();

   dal.Verify(x => x.DoSomething(), Times.Exactly(5));
}

Is this test hard to understand? Is this a valid/clean way to do this? Is there a better way? Something about writing a test this way bugs me.

+1  A: 

I think I would do something like this:

const int max = 5;
var callCount = 0;
_dal.Setup(x => x.ShouldIKeepGoing())
    .Returns(()=> ++callCount <= max )
    .AtMost(max+1);

Rhino Mocks has the ability to record each expected call in order, then replay that series of calls.

Mark
I don't seem to be able to do the AtMost call that way in Moq 3.1.416. Is this the 4.0 beta?But I think it is cleaner without the Callback, even if I have to specify the Times in my Verify.Thank you.
JohnRudolfLewis
We are using 4.0.812.4.
Mark