如何对Windows窗体应用程序进行单元测试

问题描述 投票:-1回答:2

如何对Windows窗体应用程序进行单元测试。我创建了[[Form2,我想使用nUnit测试该表单,但出现了这个错误:

消息:System.TypeInitializationException:'... Form2'的类型初始值设定项引发了异常。----> System.Threading.ThreadStateException:由于无法实例化ActiveX控件'8856f961-340a-11d0-a96b-00c04fd705a2'当前线程不在单线程单元中。

测试

[TestFixture,SingleThreaded] public class FormTest { [SetUp] public void Setup() { } [Test] public void Form_Test() { var form = new Form2(); } }

代码:表格2

public partial class Form2 : Form { public Form2() { InitializeComponent(); } public void SomeThing() { //something } }

代码:Form2.Designer

partial class Form2 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.webBrowser1 = new System.Windows.Forms.WebBrowser(); this.SuspendLayout(); // // webBrowser1 // this.webBrowser1.Dock = System.Windows.Forms.DockStyle.Fill; this.webBrowser1.Location = new System.Drawing.Point(0, 0); this.webBrowser1.MinimumSize = new System.Drawing.Size(20, 20); this.webBrowser1.Name = "webBrowser1"; this.webBrowser1.Size = new System.Drawing.Size(800, 450); this.webBrowser1.TabIndex = 0; // // Form2 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(800, 450); this.Controls.Add(this.webBrowser1); this.Name = "Form2"; this.Text = "Form2"; this.ResumeLayout(false); } #endregion private System.Windows.Forms.WebBrowser webBrowser1; }

c# winforms unit-testing
2个回答
1
投票
你不知道。您无需对所有Window逻辑都进行后备测试。您

extract您想要测试的某个类,或者甚至更好的一个接口,并针对该特定实例实例化测试。这就是为什么它称为“单元”测试的原因:与“集成”或“ end2end”测试相反,它负责测试除外部环境之外的独立软件。

除此之外,测试新表格是否确实被创建实际上是无用的。更好地关注域逻辑,域逻辑始终是错误和不良影响的主要来源。

0
投票
异常错误非常清楚:

无法实例化,因为当前线程不在单线程公寓。

向测试夹具添加SingleThreaded属性,以告知Nunit在单线程上运行测试。UI控件必须在单线程上执行。

[TestFixture, SingleThreaded] public class FormTest { public void Form_Test() { var form = new Form1(); } }

不要尝试对测试进行分类(单元,集成,验收,功能,行为,端到端等)。只有两个测试类别:快速和缓慢

Quick:是执行速度很快的测试,因此开发人员可以尽快获得有关书面代码的反馈。慢:是执行速度慢的测试,目前是涉及一些外部资源(数据库,文件系统,Web服务或UI组件)的测试。

慢速测试编写缓慢,运行缓慢,但是它们以确信应用程序能够按预期运行的形式提供了重要的价值。

可能在将来可以立即访问外部资源,这提供了编写整个应用程序测试的可能性,而无需模拟每个“单元”。

例如,这些天数据库可以在“内存中”运行,这提供了运行测试而无需完全模拟数据层的可能性。

在您的特定情况下,有一些库使您可以方便地测试winforms应用程序,只需对其进行搜索。

您可以像其他普通类一样在没有UI的情况下测试Form类,但是一旦尝试触摸UI组件,测试将失败。

如果您有某种形式的逻辑,可以在不涉及UI组件的情况下执行该逻辑,请将此逻辑移到单独的类中并自行测试该类。

© www.soinside.com 2019 - 2024. All rights reserved.