Ayende @ Wiki

The IMethodOptions allows you to set various options on a method call. Here is an example of telling Rhino Mocks to ignore the arguments of a method:

IProjectRepository repository = mocks.CreateMock<IProjectRepository>();
IProjectView view = mocks.CreateMock<IProjectView>();
Expect.Call(view.Ask(null,null)).IgnoreArguments().Return(null);
repository.SaveProject(null);
LastCall.IgnoreArguments();


As you can see, we use the Expect.Call() for methods that have return values, and LastCall for methods that return void to get the IMethodOptions interface. I find the Expect.Call() syntax a bit clearer, but there is no practical difference between the two. I would recommend using Expect wherever possible (anything that returns a value). For property setters, or methods returning void, the Expect syntax is not applicable, since there is no return value. Hence, the need for the LastCall. The idea of Last Call is pervasive in the record state, you can only set the method options for the last call - even Expect.Call() syntax is merely a wrapper around LastCall.

Expect.Call() & LastCall allow you to set the following options:

  • The return value of a method, if it has one.
    Expect.Call(view.Ask(null,null)).
      Return(null);
  • The exception the method will throw:
    Expect.Call(view.Ask(null,null)).
      Throw(new Exception("Demo"));
  • The number of times this method is expected to repeat (there are a number of convenience methods there):
    Expect.Call(view.Ask(null,null)).Return(null).
      Repeat.Twice();
  • To ignore the method arguments:
    Expect.Call(view.Ask(null,null)).Return(null).
      IgnoreArguments();
  • To set the constraints of the method:
    Expect.Call(view.Ask(null,null)).Return(null)
      .Constraints(Text.StartsWith("Some"),Text.EndsWith("Text"));
  • To set the callback for this method:
    Expect.Call(view.Ask(null,null)).Return(null).
      Callback(new AskDelegate(VerifyAskArguments));
  • To call the original method on the class:
    Expect.Call(view.Ask(null,null)).
    CallOriginalMethod();
  • To emulate simple property accessors on a property:
    Expect.Call(view.Name).
		PropertyBehavior();
  • To control programmatically what the method call will return or throw (see The Do() Handler):
    Expect.Call(view.Ask(null,null)).Do(delegate(string s1, string s2) { return s1+s2; })
    IgnoreArguments();
Note: For methods that return a value, you must specify either a return value or an exception to throw. You will not be able to continue recording or move to replay state otherwise.

Note II: Method chaining really makes writing this code easier.

Up: Rhino Mocks Documentation
Next: Rhino Mocks Setup Result

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