【发布时间】:2018-10-27 03:38:07
【问题描述】:
我有一个具有 execute() 函数的类。执行execute() 函数仅在调用 terminate() 函数时停止。我想测试一下 execute() 函数。
class Process{
public:
void execute(){ // start execution until terminate() is called.. }
void terminate(){ //stop the processing of execute()... }
}
我的单元测试用例如下。我正在使用 MSTest。
TEST_METHOD(StartTest)
{
Process p;
bool isRunning = true;
std::thread th([&](){
p.execute();
isRunning = false;
});
th.detach();
std::this_thread::sleep_for(std::chrono::milliseconds(300));
Assert::isTrue(isRunning);
}
如果使用线程是一种好的做法,我应该关闭测试用例中的线程而不是将其与主线程分离吗?
还有更好的建议。
【问题讨论】:
-
首先
isRunning没有同步。我不确定,但看起来你也没有运行线程。 -
p.execute();继续执行线程。
-
阅读有关 std::thread::detach 和 std::terminate stackoverflow.com/questions/22803600/…
-
@Boka 我的印象是构造函数也不运行线程。我错了。
标签: c++ unit-testing visual-c++ mstest