2010-05-20 70 views
2

什麼方法可以單元測試SampleConfirmationDialog? SampleConfirmationDialog將通過驗收測試來執行,但是我們如何單元測試它,因爲MessageBox不是抽象的,也沒有匹配的接口?單元測試:硬依賴MessageBox.Show()

public interface IConfirmationDialog 
{ 
    /// <summary> 
    /// Confirms the dialog with the user 
    /// </summary> 
    /// <returns>True if confirmed, false if not, null if cancelled</returns> 
    bool? Confirm(); 
} 


/// <summary> 
/// Implementation of a confirmation dialog 
/// </summary> 
public class SampleConfirmationDialog : IConfirmationDialog 
{ 
    /// <summary> 
    /// Confirms the dialog with the user 
    /// </summary> 
    /// <returns>True if confirmed, false if not, null if cancelled</returns> 
    public bool? Confirm() 
    { 
     return MessageBox.Show("do operation x?", "title", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes; 
    } 
} 

回答

5

你不能,它在目前的狀態是不可測的。對於這個特定的類,在單元測試中也沒有任何價值......它只是一個圍繞內置框架特性的輕量級包裝,所以你所做的只是測試框架。

如果您絕對必須對其進行測試,那麼IConfirmationDialog接口應該具有可以在單元測試中模擬的另一個依賴項。

+3

換句話說,您要測試'SampleConfirmationDialog',而不是'MessageBox'類。你可以抽象'IConfirmationProvider',其中一個實現可以使用'MessageBox',你可以測試'Confirm()'調用'IConfirmationProvider.GetConfirmation()',但是這對你並沒有什麼幫助 - 在某種程度上你會遇到那個無法測試的'MessageBox.' – Jay 2010-05-20 21:25:00

+0

是的,謝謝。這一個一直在竊聽我。但你們都是對的。 – 2010-05-20 21:33:36

0

你應該看看Typemock,一個商業模擬框架,它可以讓你使用.NET性能分析庫單元測試這種情況。有關更多信息,請參閱their website

0

我認爲可以在該級別停止測試。您與IConfirmationDialog的互動比驗證MessageBox.Show實際上被調用更重要。既然這是一個界面,並且很容易嘲弄,我認爲你已經很好地覆蓋了。