AB's Blog: Setup Moq to return different values on multiple calls

Thursday, March 11, 2010

Setup Moq to return different values on multiple calls

I recently came across a problem, using the Moq mocking framework, in which a few tests, required a method on one of my mocked objects to be called multiple times but return a different value depending on when the call was made. Something you can do with Rhino Mocks. But nevertheless.

The sequence may have looked something like:
Call 1: mockedObject.IsValid() returns true
Call 2: mockedObject.IsValid() returns false

My solution to the problem, which is sort of outlined in the Moq Quick Start was:

[TestMethod]
public void MultipleReturnValue_Test()
{
   bool firstCall = true;
   var mockedObject = new Mock<ISomeInterface>();

   mockedObject.Setup(o => o.IsValid()).Returns(() =>
      {
         if (firstCall == true)
         {
            firstCall = false;
            return true;
         }
         return false;
      });

   var sut = new MySystemUnderTest(mockedObject.Object);
   sut.DoSomething();

   Assert.IsTrue(sut.ExpectedCondition());
}

Not beautiful, but It works fine. The first call to IsValid() returns true, while any subsequent calls return false.

This raises the question, how much logic in a test is too much?

1 comment:

  1. I like this method better: http://haacked.com/archive/2009/09/29/moq-sequences.aspx

    ReplyDelete