2012-09-22 165 views
0

下面是一個簡單的WPF應用程序代碼的一部分:3個文本框,一個dropdownList和一個按鈕。通過點擊一個按鈕,將會檢查輸入值。WPF應用程序的單元測試

private void Button_Click_1(object sender, RoutedEventArgs e) 
    { 
     if (textBox1.Text.Length>127) 
      throw new ArgumentException(); 
     if (string.IsNullOrEmpty(textBox2.Text)) 
      errorsList.Add("You must to fill out textbox2"); 
     else if (string.IsNullOrEmpty(textBox3.Text)) 
      errorsList.Add("You must to fill out textbox3"); 
     else if 
     { 
      Regex regex = new Regex(@"........."); 
      Match match = regex.Match(emailTxt.Text); 
      if (!match.Success) 
       errorsList.Add("e-mail is inlvalid"); 
     } 
     //..... 
    } 

我必須使用任何單元測試框架來測試它。我想知道是否有可能在這裏做單元測試?我想這不是,對吧?

回答

5

不可能在沒有重構的情況下單元測試當前的代碼。您應該將該邏輯封裝在ViewModel類中。我想你可以有類似

DoTheJob(string1,string2,string3,...) 

error/errorList/exList作爲ObservableCollections到viev模型了。 有了這些先決條件,你可以編寫一套單元測試來檢查你的代碼行爲。

1

所以基本上你需要它代表你的UI

 public class ViewModel 
    { 
     public ViewModel() 
     { 
      ButtonClickCommand = new RelayCommand(Validate); 
     } 

     private void Validate() 
     { 
      if (Text1.Length > 127) 
       throw new ArgumentException(); 
      if (string.IsNullOrEmpty(Text2)) 
       ErrorList.Add("You must to fill out textbox2"); 
      else if (string.IsNullOrEmpty(Text3)) 
       ErrorList.Add("You must to fill out textbox3"); 
      else 
      { 
       Regex regex = new Regex(@"........."); 
       Match match = regex.Match(Email); 
       if (!match.Success) ErrorList.Add("e-mail is inlvalid"); 
      } 
     } 

     public string Text1 { get; set; } 
     public string Text2 { get; set; } 
     public string Text3 { get; set; } 
     public string Email { get; set; } 
     public ObservableCollection<string> ErrorList { get; set; } 
     public ICommand ButtonClickCommand { get; private set; } 
    } 

和視圖模型的實例應該連接到你的控制/窗口的DataContext屬性一個視圖模型類。

在這種方法中,你可以單元測試你的ViewModel所有你想要的:)

0

的方式嘛,如果你命令綁定您的按鈕

<Button Command="{Binding SayHello}">Hello</Button> 

然後在你的單元測試,你應該能夠執行按鈕上的命令。

var button = GetMyButton(); 
button.Command.Execute(new object());