Skip to main content
 首页 » 编程设计

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

2024年09月07日32rubylouvre

有没有人对单元测试多线程应用程序的一致方式有任何建议?我已经完成了一个应用程序,其中我们的模拟“工作线程”有一个 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)); 

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