如何使用 Rhino Mocks/簡介
外觀
1. 建立一個模擬儲存庫
MockRepository mocks = new MockRepository();
2. 將一個模擬物件新增到儲存庫中
ISomeInterface robot = (ISomeInterface)mocks.CreateMock(typeof(ISomeInterface));
如果您使用的是 C# 2.0,您可以使用泛型版本,避免向上轉型
ISomeInterface robot = mocks.CreateMock<ISomeInterface>();
3. “記錄”您希望在模擬物件上呼叫的方法
// 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();
請注意,這些呼叫中提供的引數值代表我們希望模擬物件被呼叫的值。類似地,返回值代表當呼叫此方法時模擬物件將返回的值。
您可以預期一個方法被多次呼叫
// 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. 將模擬物件設定為“回放”狀態,在呼叫時,它將回放剛剛記錄的操作。
mocks.ReplayAll();
5. 呼叫使用模擬物件的程式碼。
theButler.GetRobotReady();
6. 檢查是否對模擬物件進行了所有呼叫。
mocks.VerifyAll();