C# 如何测试按钮单击是否会打开带有NUnitForms的新表单?
我是C#新手,试图用NUnit和NUnitForms编写一个简单的GUI单元测试。我想测试一下点击按钮是否会打开一个新表单。 我的应用程序有两个表单,主表单(Form1)带有打开新表单(密码)的按钮: 我的测试的源代码如下所示:C# 如何测试按钮单击是否会打开带有NUnitForms的新表单?,c#,unit-testing,nunit,C#,Unit Testing,Nunit,我是C#新手,试图用NUnit和NUnitForms编写一个简单的GUI单元测试。我想测试一下点击按钮是否会打开一个新表单。 我的应用程序有两个表单,主表单(Form1)带有打开新表单(密码)的按钮: 我的测试的源代码如下所示: using NUnit.Framework; using NUnit.Extensions.Forms; namespace Foobar { [TestFixture] public class Form1Test : NUnitFormTest
using NUnit.Framework;
using NUnit.Extensions.Forms;
namespace Foobar
{
[TestFixture]
public class Form1Test : NUnitFormTest
{
[Test]
public void TestNewForm()
{
Form1 f1 = new Form1();
f1.Show();
ExpectModal("Enter Password", "CloseDialog");
// Check if Button has the right Text
ButtonTester bt = new ButtonTester("button2", f1);
Assert.AreEqual("Load Game", bt.Text);
bt.Click();
}
public void CloseDialog()
{
ButtonTester btnClose = new ButtonTester("button2");
btnClose.Click();
}
}
}
NUnit输出为:
NUnit.Extensions.Forms.FormsTestAssertionException : expected 1 invocations of modal, but was invoked 0 times (Form Caption = Enter Password)
按钮文本检查成功。问题在于ExpectModal方法。我也尝试过使用表单的名称,但没有成功
有人知道可能出了什么问题吗?我自己想出来的。有两种方式可以显示Windows窗体:
- 模态:“在继续使用应用程序的其余部分之前,必须关闭或隐藏模态窗体或对话框”
- 无模式:“…允许您在表单和其他表单之间转移焦点,而无需关闭初始表单。当表单显示时,用户可以继续在任何应用程序中的其他位置工作。”
我将源代码中的每个“Show()”都更改为“ShowDialog()”,NUnitForms工作正常。如果您希望表单实际作为模式对话框打开,我只会将源代码更改为使用ShowDialog() 您是正确的,NUnitForms支持“Expect-Modal”,但没有“Expect-Non-Modal”。使用FormTester类,您可以相对轻松地实现这一点。FormTester是NUnitForms的最新存储库中提供的扩展类。传入要检查的表单的.Name属性的字符串,以查看是否显示该属性
public static bool IsFormVisible(string formName)
{
var tester = new FormTester(formName);
var form = (Form) tester.TheObject;
return form.Visible;
}
public static bool IsFormVisible(string formName)
{
var tester = new FormTester(formName);
var form = (Form) tester.TheObject;
return form.Visible;
}