我目前正在为旧版 Windows 窗体应用程序编写系统测试。
在我的测试中,我调用了该Program.Main()
方法,该方法又Application.Run(new MainForm());
在某个时候调用。
有没有办法用我可以控制的东西替换 Application.Run() ?
具体来说,我需要能够停止执行并捕获未处理的异常。
我目前正在为旧版 Windows 窗体应用程序编写系统测试。
在我的测试中,我调用了该Program.Main()
方法,该方法又Application.Run(new MainForm());
在某个时候调用。
有没有办法用我可以控制的东西替换 Application.Run() ?
具体来说,我需要能够停止执行并捕获未处理的异常。
您可以修改 Program.Main 以接受表单作为输入参数,默认为 MainForm。引用类型不能有非空默认值,但我们可以通过使用两个原型来完成同样的事情:
class Program
{
//Normal entry point
static public void Main()
{
Main(new MainForm());
}
//Internal & test entry point
static public void Main(Form form)
{
DoSomeSetup();
Application.Run(form);
}
}
当您以正常方式运行程序时,它将使用MainForm
.
但是当你从你的测试项目中运行它时,你可以这样调用它:
Program.Main(new FormICanControl());
然后你可以控制它。
//Arrange
var t = new TestForm();
//Act
Program.Main(t);
t.ExecuteSomeTest();
//Assert
Assert.AreEqual(t.ResultCode, 0, "Test failed.");
.Abort()
作为最后的手段杀死主线程。Application.ThreadExceptionHandler
AppDomain.CurrentDomain.UnhandledException
Application
可能是个问题,因为人们经常通过调用 Application.DoEvents(..) 来做一些技巧,并使用消息泵做其他事情。