Search code examples
c#unit-testingmockingrhino-mocks

Is it possible to train Rhinomocks for arbitrary input?


I am trying to set up a unit test for a piece of code that uses a spelling corrector. I have the code properly dependency injected, so setting up the stub in Rhinomocks is not a problem, but the block of text I've created for the test is a good 50 words long and I would really rather not have 50 lines of code that look something like this:

spellingCorrector.Stub(x => x.CorrectWord("the")).Return("the");
spellingCorrector.Stub(x => x.CorrectWord("boy")).Return("boy");
spellingCorrector.Stub(x => x.CorrectWord("ran")).Return("ran");

For the purposes of my unit tests I think assuming that the words are spelled right is okay. Is there a way to get Rhinomocks to simply follow a rule about returning, something to the effect of:

spellingCorrector.Stub(x => x.CorrectWord(y)).Return(y);

Solution

  • You could use the IgnoreArguments() method:

    spellingCorrector
        .Stub(x => x.CorrectWord(null))
        .IgnoreArguments()
        .Return(y);
    

    This way no matter what value is passed to the CorrectWord method, it will return y.


    UPDATE:

    After your comment it is more clear:

    Func<string, string> captureArg = arg => arg;
    spellingCorrector.Stub(x => x.CorrectWord(null)).IgnoreArguments().Do(captureArg);
    

    This will use whatever value is passed as argument as return value. Adapt the captureArg delegate if you need to perform some transformations on this return value.