Friday, August 15, 2008

[Rhino] Mock Anomalies: Setup Stub Once Call Multiple Times - Must Call .Stub<T> and SetupResult

I was hooking up multiple times because otherwise it was giving me grief.  Here's the test that seems to work the way I intended (for setting up a stub method once and call it multiple times.

[TestMethod]
public void TestSetupStubOnceCallMultipleTimes()
{
    //IDemo partialStub = MockRepository.GenerateStub<IDemo>();
    IDemo partialStub = new MockRepository().Stub<IDemo>();
 
    //This line does not work unless I have called the above .Stub<IDemo>
    partialStub
        .Stub<IDemo, string>((x) => { return x.ReturnStringWithInt32Arg(30); })
        .IgnoreArguments()
        .Do(
            (Func<int, string>)((arg) =>
            {
                return string.Format(
                    "{0}{1}",
                    new string('0', 6 - arg.ToString().Length), arg);
            })
        );
 
    //If I comment the above line out, it gives me this error on SetupResult below
    //Test method ThinkFarAhead.LearningMocking.Expectations.SetupResult2.TestRhinoAndMoq.Working threw exception:
    //System.InvalidOperationException: Invalid call, the last call has been used or 
    //no call has been made (make sure that you are calling a virtual (C#) / Overridable (VB) method)..
    //This error occurs both when I create the Stub using 
    //MockRepository.GenerateStub<IDemo>() or new MockRepository().Stub<IDemo>()
    SetupResult.For((Action<IDemo>)(x => x.ReturnStringWithInt32Arg(30))).IgnoreArguments()
      .Do((Func<int, string>)((arg) =>
      {
          return string.Format(
              "{0}{1}",
              new string('0', 6 - arg.ToString().Length), arg);
      }
        ));
 
 
    partialStub.Replay();
    Assert.AreEqual("000020", partialStub.ReturnStringWithInt32Arg(20));
    Assert.AreEqual("000030", partialStub.ReturnStringWithInt32Arg(30));
    Assert.AreEqual("000040", partialStub.ReturnStringWithInt32Arg(40));
}

1 comment:

Helen said...

Nice and clear review. But I think beginners still need the basics to fully grasp what's going on here.

Helen Neely