gpt4 book ai didi

C# 单元测试控制调用问题

转载 作者:行者123 更新时间:2023-11-30 18:27:10 25 4
gpt4 key购买 nike

我已经为 WinForms 应用编写了单元测试。该应用程序在线程中执行代码,该代码在 UI 上设置结果。为此,我必须通过 Control.Invoke(delegate) 在 UI 线程中调用结果集。在应用程序中它运行完美。在单元测试中,我必须等待异步结果。但是,在单元测试中,Control.Invoke(delegate) 不会触发。

我没有线程问题。线程在单元测试中工作完美。问题是在 UI 线程上调用形成线程。有没有人有提示,它是如何工作的。

为了重现这个问题,我创建了一个示例 WinForms 项目和一个单元测试项目。表单包含一个文本框和一个按钮。通过单击按钮,它会启动一个线程,等待两秒钟并在文本框中设置一个文本。设置文本后,它会触发一个事件。

这是表单类:

public partial class TestForm : Form
{
public TestForm()
{
InitializeComponent();
}

private void btnAction_Click(object sender, EventArgs e)
{
this.SetText();
}

public delegate void delFinish();
public event delFinish Finish;

public void SetText()
{
Thread runner = new Thread(() => {
Thread.Sleep(2000);

if (this.txtResult.InvokeRequired)
this.txtResult.Invoke((MethodInvoker)(() =>
{
this.txtResult.Text = "Runner";

if (Finish != null)
Finish();
}));
else
{
this.txtResult.Text = "Runner";

if (Finish != null)
Finish();
}

});
runner.Start();
}
}

这是单元测试:

[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
ManualResetEvent finished = new ManualResetEvent(false);

TestForm form = new TestForm();

form.Finish += () => {
finished.Set();
};

form.SetText();

Assert.IsTrue(finished.WaitOne());

Assert.IsTrue(!string.IsNullOrEmpty(form.txtResult.Text));
}
}

问题是这一行不会执行:

              this.txtResult.Invoke((MethodInvoker)(() =>

感谢您的帮助!

最佳答案

问题是,在上面的示例中,当前线程被阻塞,但控件想要在该线程上调用。

解决方案是将其他事件 Application.DoEvents() 和 yield 执行交给另一个线程 Thread.Yield()。

测试方法如下:

    [TestMethod]
public void TestMethod1()
{
bool finished = false;

TestForm form = new TestForm();

form.Finish += () =>
{
finished = true;
};

form.SetText();

while (!finished)
{
Application.DoEvents();
Thread.Yield();
}

Assert.IsTrue(!string.IsNullOrEmpty(form.txtResult.Text));
}

希望这对某些人有帮助。

关于C# 单元测试控制调用问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27186371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com