Ayende @ Wiki

There are times when the returning a static value is not good enough for the scenario that you are testing, so for those cases, you can use the Do() handler to add custom behavior when the method is called. In general, the Do() handler simply replaces the method call. Its return value will be returned from the mocked call (as well as any exception thrown). The handler's signature must match the method signature, since it gets the same parameters as the call.

Let's see an example. A speaker object can introduce itself formally or informally, so we'll separate the name creation into a separate class. We want to test the speaker in isolation and mock the name creation, so we use this code (contrived again, I'm afraid):
public void SayHelloWorld()
  INameSource nameSource = mocks.CreateMock<INameSource>();
      Do(new NameSourceDelegate(Formal));
  string expected = "Hi, my name is Ayende Rahien";
  string actual = new Speaker("Ayende", "Rahien", nameSource).Introduce();
  Assert.AreEqual(expected, actual);
 delegate string NameSourceDelegate(string first, string surname);
 private string Formal(string first, string surname)
  return first + " " +surname;

public class Speaker { private readonly string firstName; private readonly string surname; private INameSource nameSource ; public Speaker(string firstName, string surname, INameSource nameSource) { this.firstName = firstName; this.surname = surname; this.nameSource = nameSource; } public string Introduce() { string name = nameSource.CreateName(firstName, surname); return string.Format("Hi, my name is {0}", name); } } public interface INameSource { string CreateName(string firstName, string surname); }

Note: The Do() handler is only called if the method was matched, and it is called once per method match. This is different from Callback(), which may be called many times.

Maintainability note: If you've a complex logic going on for the test, you should consider making a class manually, it will probably be easier in the long run.

Up: Rhino Mocks Documentation
Next: Rhino Mocks Constraints

ScrewTurn Wiki version 2.0 Beta. Some of the icons created by FamFamFam.