2011-08-17 35 views
1

我正在使用Typemock進行一些單元測試。我嘲笑靜態類Widget。我想嘲笑Widget.GetPrice(123)的返回返回值A.驗證具有特定參數的方法未使用TypeMock調用

Isolate.Fake.StaticMethods<Widget>(); 
Isolate.WhenCalled(() => Widget.GetPrice(123)).WillReturn("A"); 

我也想驗證Widget.GetPrice(456)不叫。

Isolate.Verify.WasNotCalled(() => Widget.GetPrice(456)); 

看來WasNotCalled沒有考慮參數。測試回來說它失敗B/W Widget.GetPrice實際上被稱爲。

我認爲這樣做的唯一方法是在調用Widget.GetPrice(456)時執行DoInstead調用並增加計數器。測試結束時會檢查計數器是否增加。有沒有更好的方法來做到這一點?

回答

3

有幾種方法可以做到這一點。

首先,你DoInstead的想法是不錯,但我會調整它包含一個斷言:

Isolate.WhenCalled(() => Widget.GetPrice(0)).DoInstead(
    context => 
    { 
    var num = (int)context.Parameters[0]; 
    Assert.AreNotEqual(456, num); 
    return "A"; 
    }); 

的思路是,當方法被調用,您驗證在調用的時候,傳入的參數是您期望的,如果不是,則使用Assert語句進行測試失敗。 (你也會注意到我把「0」作爲參數,因爲正如你注意到的那樣,實際值並不重要,我發現在將來的維護中使用null/0/etc更容易,不要緊,所以你不要「忘記」或「被愚弄」,認爲它確實很重要。)

你可以做的第二件事是使用WithExactArguments來控制行爲。

// Provide some default behavior that will break things 
// if the wrong value comes in. 
Isolate 
    .WhenCalled(() => Widget.GetPrice(0)) 
    .WillThrow(new InvalidOperationException()); 

// Now specify the right behavior if the arguments match. 
Isolate 
    .WhenCalled(() => Widget.GetPrice(123)) 
    .WithExactArguments() 
    .WillReturn("A"); 

的「WithExactArguments」會讓你的行爲來看僅在參數匹配。當你運行你的測試時,如果一個無效值被傳入,這個異常將被拋出,測試將失敗。

無論哪種方式,您最終都會使用「WhenCalled」部分來處理您的斷言,而不是「驗證」調用。

2

聲明,我在Typemock工作。

由於我們的API不斷改進,請查看您的問題的另一個解決方案。您可以使用

Isolate.WhenCalled((<type arg1>, <type arg1>) => fake<method> (<arg1>, <arg2>)).AndArgumentsMatch((<arg1>, <arg2>) => <check>.<behavior>; 

用於設置您想要的參數的行爲。

另外,不需要拋出任何異常。使用DoInstead()如下所示來驗證哪些方法沒有用確切的參數調用。沒有內在的斷言是必要的。

[TestMethod, Isolated] 
public void TestWidget() 
{ 
    Isolate.WhenCalled((int n) => Widget.GetPrice(n)).AndArgumentsMatch((n) => n == 123).WillReturn("A"); 

    bool wasCalledWith456 = false; 

    Isolate.WhenCalled(() => Widget.GetPrice(456)).WithExactArguments().DoInstead((context) => 
    { 
     wasCalledWith456 = true; 
     context.WillCallOriginal(); 
     return null; 
    }); 

    Assert.AreEqual("A", Widget.GetPrice(123)); 
    Widget.GetPrice(234); 
    Widget.GetPrice(345); 
    Widget.GetPrice(456); 

    Assert.IsFalse(wasCalledWith456); 
} 
相關問題