2015-04-06 64 views
1

我試圖在wpf應用程序中測試我的viewmodels。我在我的viewmodel中執行一個包含確認對話框的方法。我需要運行所有的單元測試,以便每次打開這些對話框時都需要手動確認。C#wpf UnitTesting viewmodels

我的問題是有什麼辦法,我可以編程方式知道哪個方法有確認對話框,並以編程方式點擊「確定」或「取消」?

+0

你用什麼代碼來顯示確認對話框? – 2015-04-06 19:50:47

回答

0

對此的最佳解決方案可能不是嘗試以編程方式單擊「確定」或「取消」,而是防止在運行單元測試時創建對話框。

要做到這一點,你需要一個抽象用於獲取用戶確認,這樣的事情:

public interface IUserConfirmation 
{ 
    bool Confirm(string title, string message); 
} 

在你的命令的執行,方法,你只能用這種抽象而不是實際顯示一個對話框:

public class ViewModel 
{ 
    private void MyCommandExecuted(object parameter) 
    { 
     if (this.confirmation.Confirm("Please confirm", "Are you sure you want to ...?") 
     { 
      ... 
     } 
    } 

現在你創建這個接口的兩個實現:一是這實際上顯示一個對話框,用戶和另一個只返回一個預先配置的值。在您的主應用程序中,您使用「真實」對話框實現,並在您的單元測試中使用「假」實現。

爲了做到這一點,你需要能夠在您的視圖模型通過構造「注入」不同的實現方式,例如:

public ViewModel(IUserConfirmation confirmation) 
{ 
    if (confirmation == null) 
     throw new ArgumentNullException("confirmation"); 

    this.confirmation = confirmation; 
} 

private readonly IUserConfirmation confirmation; 

這實際上就是所謂的「依賴注入一個衆所周知的模式」。有可用的框架可以幫助您創建對象,但對於像這樣的簡單案例,它們不是必需的。

下面是兩個實現可能看起來像:

public class MessageBoxUserConfirmation : IUserConfirmation 
{ 
    public bool Confirm(string title, string message) 
    { 
     return MessageBox.Show(title, message) == true; 
    } 
} 

public class TestUserConfirmation: IUserConfirmation 
{ 
    public bool Result { get; set; } 

    public bool Confirm(string title, string message) 
    { 
     return this.Result; 
    } 
} 

在單元測試中,使用這樣的:

var confirmation = new TestConfirmation(); 
var viewModel = new ViewModel(confirmation); 

// simulate a user clicking "Cancel" 
confirmation.Result = false; 

viewModel.MyCommand.Execute(...); 

// verify that nothing happened 

也有框架,而無需創建這些假冒的實現隨時編寫你自己的類,但是對於那些簡單的例子,你可能不需要它們。

+0

非常感謝Daniel的回答。我會嘗試試驗你的建議並讓你知道結果。 – 2015-04-11 18:07:26