A reminder post for me on how to use the Rhino.Mocks Do() handler together with anonymous delegates. This is useful when you want to set a method call expectation and the method accepts some complex type as the parameter. Using assertions you can set expectations for the parameter’s value with your own custom logic. There are other ways of achieving this, off course, but this way is elegant for simple (few lines of code) cases.

The example code starts with defining an IStringProcessor interface (which will be mocked):


    public interface IStringProcessor
    {
        void ProcessString (string value);
    }

This is an example interface, just to demonstrate the power of Do() handler.

In the test method we want to make sure that all calls to the IStringProcessor.ProcessString() method provide strings which contain the ‘text’ substring. We then do the test by calling this method with three different string parameters:


    [Test]
    public void RhinoDoExample ()
    {
        IStringProcessor mockProcessor = mocks.CreateMock <IStringProcessor> ();

        mockProcessor.ProcessString (null);
        LastCall.IgnoreArguments ().Do ((Action<string>)delegate (string value)
            {
                Assert.IsTrue (value.Contains ("text"));
            }).Repeat.Any();

        mocks.ReplayAll();

        mockProcessor.ProcessString ("This is a dummy text.");
        mockProcessor.ProcessString ("This is a dummy text2.");
        mockProcessor.ProcessString ("This is a dummy.");

        mocks.VerifyAll();
    }

The test method will fail because of the third call: “This is a dummy.” string does not contain the required ‘text’ substring.