How to Use Rhino Mocks/Introduction
1. Create a mock repository:
MockRepository mocks = new MockRepository();
2. Add a mock object to the repository:
ISomeInterface robot = (ISomeInterface)mocks.CreateMock(typeof(ISomeInterface));
If you're using C# 2.0, you may use the generic version and avoid upcasting:
ISomeInterface robot = mocks.CreateMock<ISomeInterface>();
3. "Record" the methods that you expect to be called on the mock object:
// this method has a return type, so wrap it with Expect.Call Expect.Call(robot.SendCommand("Wake Up")).Return("Groan"); // this method has void return type, so simply call it robot.Poke();
Note that the parameter values provided in these calls represent those values we expect our mock to be called with. Similary, the return value represents the value that the mock will return when this method is called.
You may expect a method to be called multiple times:
// again, methods that return values use Expect.Call Expect.Call(robot.SendCommand("Wake Up")).Return("Groan").Repeat.Twice(); // when no return type, any extra information about the method call // is provided immediately after via static methods on LastCall robot.Poke(); LastCall.On(robot).Repeat.Twice();
4. Set the mock object to a "Replay" state where, as called, it will replay the operations just recorded.
5. Invoke code that uses the mock object.
6. Check that all calls were made to the mock object.