Mock object framework (3)

Source: The art of unit testing with examples in .NET, Roy Osherove
http://www.amazon.com/Art-Unit-Testing-Examples-Net/dp/1933988274/ref=sr_1_1?ie=UTF8&s=books&qid=1267086529&sr=1-1
Chapter 5 Isolation (mock object) framework

有關return value的問題
大家對於被mock 的部份要如何傳回值應該會有興趣, 這裡讓我們看看Rhino Mock可以怎麼做

[Test]
public void Analyze_TooShortFileName() {
  // create dynamic mock object
  MockRepository mocks = new MockRepository();
  IGetResults resultGetter = mocks.DynamicMock();
 
  using(mocks.Record()) {
    resultGetter.GetSomeNumber("a");
    // 利用LastCall指定呼叫到這個函式時, 要傳回什麼值
    // mock object會紀錄參數, 函式名稱, 和傳回質的對應關係
    LastCall.Return(1);
   
    resultGetter.GetSomeNumber("a");
    LastCall.Return(2);
   
    resultGetter.GetSomeNumber("b");
    LastCall.Return(3);
  }
 
  int result = resultGetter.GetSomeNumber("b");
  Assert.AreEqual(3, result);
 
  int result = resultGetter.GetSomeNumber("a");
  Assert.AreEqual(1, result);

  int result = resultGetter.GetSomeNumber("a");
  Assert.AreEqual(2, result);
}

你會發現到在設定expectation時, 函式的呼叫順序和實際測試時的呼叫順序不同, 可是上面這段程式仍然會通過. 如果你覺得順序很重要, 你可以參考Rhino Mock的網站, 有ordered mocks可以使用.

你會問到是否只能設定傳回值是數字, 若是要傳回object, 或是叫delegate來處理, 是否也可以. Rhino Mock真的是滿強的, 你可以這樣做
LastCall.Throw(Exception);
或者
LastCall.Do( yourDelegateHere );

arrow
arrow
    全站熱搜

    kojenchieh 發表在 痞客邦 留言(0) 人氣()