2012-09-22 7 views
0

다음은 간단한 WPF 응용 프로그램 코드의 일부로 3 개의 텍스트 상자, 드롭 다운 목록 및 단추가 있습니다. 버튼을 클릭하면 입력 값을 확인할 수 있습니다.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 클래스에 캡슐화해야합니다. 난 당신이 너무에 Viev 모델에 ObservableCollections

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

error/errorList/exList 같은 것을 할 수 있습니다 같아요. 이러한 전제 조건을 사용하여 코드 동작을 검사하는 단위 테스트 스위트를 작성할 수 있습니다.

1

그래서 기본적으로 당신은 당신의 제어/윈도우의 DataContext 속성에 연결해야합니다 귀하의 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; } 
    } 

그리고 뷰 모델의 인스턴스를 나타내는 뷰 모델 클래스가 필요합니다. 이 방법에서

, 당신은 단위 당신이

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

당신의 단위 테스트 당신이 실행할 수 있어야합니다 귀하의 버튼 바인딩 명령을 잘 경우의 ViewModel 당신이 :)

0

을 원하는 모든 방법을 테스트 할 수 있습니다 버튼의 명령.

var button = GetMyButton(); 
button.Command.Execute(new object()); 
관련 문제