gpt4 book ai didi

c# - 如何在单元测试中处理后台线程中的异常?

转载 作者:太空狗 更新时间:2023-10-29 21:31:30 24 4
gpt4 key购买 nike

我正在编写单元测试套件来测试 TCP/IP 通信库。

当我使用 BeginAcceptClient 和 EndAcceptClient 时,消息是在后台线程中接收的。

收到消息后,我对其执行一些断言,但如果任何断言失败,VSTestHost.exe 就会崩溃。

我用谷歌搜索了一下,发现它是在后台线程中抛出 Assert 异常的事实。

编辑:我正在做的示例代码,只是为了说明:


public void TestFooMessage() {
Server.OnReceive += (s, e) => {
Assert.IsInstanceOfType(e.Message, typeof(Foo));
};

var message = new Foo();
Client.Send(message);
}

有谁知道如何让它按预期工作:记录断言并继续正常运行?

最佳答案

你不应该在后台线程(比如:后台事件处理程序)中编写断言,因为测试框架无法处理这个。你应该只在那里收集值(value)。例如,您可以使用 AutoResetEvents 同步主线程。将值写入字段,在主线程断言字段。

如果消息永远不会进来,您需要超时。

一点伪代码(其实不是那么伪):

private AutoResetEvent ReceiveEvent = new AutoResetEvent(false);
private EventArgs args;
private bool ReceiveCalled = false;

// event handler with some argument
private void Receive(object sender, EventArgs args)
{
// get some arguments from the system under test
this.args= args;

// set the boolean that the message came in
ReceiveCalled = true;

// let the main thread proceed
ReceiveEvent.Set();
}

[TestMethod]
public void Test()
{
// register handler
Server.OnReceive += Receive;

var message = new Foo();
Client.Send(message);

// wait one second for the messages to come in
ReceiveEvent.WaitOne(1000);

// check if the message has been received
Assert.IsTrue(
ReceiveCalled,
"AcceptClientReceived has not been called");

// assert values from the message
Assert.IsInstanceOfType(args.Message, typeof(Foo))
}

顺便说一句:您仍然可以将处理程序编写为 lambda 表达式,甚至可以通过使用局部变量来避免字段。但如果所有内容都在一个方法中,可能会更难阅读。

关于c# - 如何在单元测试中处理后台线程中的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1488817/

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