在单元测试方法中显示 Windows 窗体 [英] Displaying Windows Forms inside unit test methods

查看:24
本文介绍了在单元测试方法中显示 Windows 窗体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在 Visual Studio .NET 中发现了单元测试项目,并且正在使用测试方法来设置我开发的全局代码示例.

I just discovered unit test projects in Visual Studio .NET and am using test methods to set up examples of global code I have developed.

一些全局方法涉及显示可重复使用的对话框,如日期选择器和输入框.问题是,有时表单会显示,有时则不会.

Some global methods involve displaying reusable dialogs like a date-picker and input box. Trouble is, sometimes forms will display and sometimes they won't.

我以为和模态有关,因为我有一个可以模态或非模态显示的报告预览表单.当我以非模态方式显示时,它不会显示.当我以模态方式显示时,它确实如此.

I thought it was related to modality, because I have a report preview form that can be shown modally or non-modally. When I show that non-modally, it does not display. When I show it modally, it does.

尝试我的输入框永远不起作用:

Trying my input box never works:

string input = "";
using (InputBox box = new InputBox(Title, Prompt, Default))
{
    DialogResult result = box.ShowDialog();
    input = box.txtInput.Text.Trim();
}
return input;

执行在box.ShowDialog()"行停止,此时我可以检查 box 并看到它的尺寸、位置和可见性都已正确配置——但我看不到表单.我必须取消测试以停止一切.

Execution stops at the "box.ShowDialog()" line, and at that point I can inspect box and see that its dimensions, location, and visibility are all properly configured -- yet I cannot see the form. I've got to cancel the test to stop everything.

我很想使用单元测试项目来充当现有代码的游乐场和展示区,但如果我无法显示某些表单,这似乎非常有限.我意识到这并不是单元测试的真正意义,但我希望我可以通过这种方式构建一个有趣的小沙箱,以帮助我的开发人员加快速度.

I'd love to use a unit testing project to act as a playground and showcase of existing code, but it seems very limited if I can't display certain forms. I realize this is not really what unit testing is meant for, but I hoped I could build a fun little sandbox this way to help get my developers up to speed.

推荐答案

基于单个表单属性:ShowInTaskbar,我终于取得了一些一致的成功(但缺乏成功).

I finally had some consistent success (and lack thereof) based on a single form property: ShowInTaskbar.

当表单将该属性设置为 true 时,此类表单将不会从单元测试方法中显示.当该属性为 false 时,将显示所有表单.因此,据我所知,以下是确保表单可以从单元测试中显示的规则:

When a form had that property set to true, such forms would NOT display from a unit test method. When that property is false, all forms display. So, here are the rules as far as I know them to make sure a form can display from a unit test:

  • 应将表单创建为项目中的标准 Windows 表单项.
  • 表单应将其 ShowInTaskbar 属性设置为 FALSE.
  • 表单需要以模态显示(即使用 ShowDialog()).

这让我可以显示和测试所有实用程序表单,例如日期选择器和登录屏幕.

This has let me display and test all of my utility forms like date selectors and login screens.

这篇关于在单元测试方法中显示 Windows 窗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆