【问题标题】:Create unit test for Windows Form. .Net C#为 Windows 窗体创建单元测试。 .Net C#
【发布时间】:2013-03-28 16:16:38
【问题描述】:

有一种形式,其中有控件(文本框,按钮)。

public partial class Form1 : Form
    {


        public MWLogin()
        {
            InitializeComponent();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
                this.DialogResult = System.Windows.Forms.DialogResult.OK;


          }

    //there is text box!

        private void txtbox_SelectedIndexChanged(object sender, EventArgs e)
            {
            if(!String.IsNullorEmpty(txtbox.Text))
            {
                btnOK.Enabled = true;   //for example
            }
        }
}

在单元测试中应该从 txtBox 获取文本 例如:(不正确)

[TestMethod()]
            public void Form1Test()
            {
            try
            {

                MWLogin target = new MWLogin();
                if(MWLogin.ShowDialog() == DialogResult.OK)
                {
                      string a = MWLogin.txtBox.Text; //this is no correct
                }

                Assert.IsTrue(true);
            }
            catch (Exception)
            {
                Assert.Fail();
            }
        }

请帮忙!如何在表单中从txtBox 获取文本(表单中没有静态或公共属性)

【问题讨论】:

  • 试试target.txtBox.Text。但有些不对劲。你的班级是Form1,但构造函数是MWLogin
  • 一个错字)只是一个例子。是的,应该有 Form1 target = new Form1();

标签: .net winforms unit-testing c#-4.0


【解决方案1】:

您不能访问私人成员(txtbox 是私人的)。尝试添加公共属性:

public String TextBoxText { get { return txtbox.Text; } }

现在在单元测试中你可以使用:

string a = target .TextBoxText;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-28
    • 2016-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多