gpt4 book ai didi

.net - 对多线程应用程序进行单元测试?

转载 作者:行者123 更新时间:2023-12-03 08:52:05 30 4
gpt4 key购买 nike

有没有人对单元测试多线程应用程序的一致方式有任何建议?我已经完成了一个应用程序,其中我们的模拟“工作线程”有一个 thread.sleep,其时间由公共(public)成员变量指定。我们将使用它,以便我们可以设置特定线程完成其工作所需的时间,然后我们可以进行断言。有更好的方法来做到这一点吗?有什么好的.Net 模拟框架可以处理这个问题吗?

最佳答案

如果您必须测试后台线程是否执行某些操作,我觉得很方便的一个简单技术是拥有一个 WaitUntilTrue 方法,它看起来像这样:

bool WaitUntilTrue(Func<bool> func,
int timeoutInMillis,
int timeBetweenChecksMillis)
{
Stopwatch stopwatch = Stopwatch.StartNew();

while(stopwatch.ElapsedMilliseconds < timeoutInMillis)
{
if (func())
return true;
Thread.Sleep(timeBetweenChecksMillis);
}
return false;
}

像这样使用:
volatile bool backgroundThreadHasFinished = false;
//run your multithreaded test and make sure the thread sets the above variable.

Assert.IsTrue(WaitUntilTrue(x => backgroundThreadHasFinished, 1000, 10));

这样,您不必让主测试线程长时间休眠以让后台线程有时间完成。如果后台没有在合理的时间内完成,则测试失败。

关于.net - 对多线程应用程序进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/111676/

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