0

以下は単純な WPF アプリケーションのコードの一部です: 3 つのテキスト ボックス、dropdownList、およびボタン。ボタンをクリックすると、入力値のチェックが行われます。

   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");
        }
        //.....
     }

単体テスト フレームワークを使用してテストする必要があります。ここで単体テストを行うことは可能でしょうか? そうではないと思いますよね?

4

3 に答える 3

5

リファクタリングせずに現在のコードを単体テストすることはできません。そのロジックを ViewModel クラスにカプセル化する必要があります。私はあなたがのようなものを持つことができると思います

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

そしてerror/errorList/exListvievObservableCollectionsモデルにも。これらの前提条件により、コードの動作をチェックする一連の単体テストを作成できます。

于 2012-09-22T05:43:51.480 に答える
0

したがって、基本的には、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; }
    }

ViewModel のインスタンスは、コントロール/ウィンドウの DataContext プロパティにアタッチする必要があります。

このアプローチでは、ViewModel を必要な方法で単体テストできます:)

于 2012-09-23T11:14:49.440 に答える