我们可以在 C++ 中使用 Google Test/Gmock 模拟调用 std::thread 函数的函数吗?

问题描述

我可以模拟调用 std::thread 函数函数吗。

例如 创建线程:

std::thread thread_id

void myfun()
{
thread_id = std::thread(&threadfunction,this);
logger_.Info(LOG001,"Myfun() is called");
}

在另一个函数中加入一个线程

void final()
{
    if (thread_id.joinable())
      thread_id.join();
}

在测试部分:

TEST_F(mytest,myfun)
{
EXPECT_CALL(logger_mock_,Info(LOG001,::testing::_)); //logging expect call
my_class_.myfun();  //my_class_ is instance object.
}

我想测试这个函数,但我收到错误“终止调用而没有活动异常”。 这意味着线程被创建并超出范围并且测试终止。 :(

是否可以在 gmock 中使用 std::thread?

我还从以下文档中了解到 pthread 用于多线程 Google 测试:

https://chromium.googlesource.com/external/github.com/google/googletest/+/refs/tags/release-1.8.0/googletest#multi-threaded-tests

请帮忙解决这个问题。

解决方法

在单独线程中使用的模拟上设置期望调用没有问题。您对 terminate called without an active exception. 的问题是您创建了一个从未加入的线程。试试:

void myfun()
{
    auto t = std::thread(&threadfunction,this);
    logger_.Info(LOG001,"Myfun() is called");
    t.join();
}

但请注意,logger_.Info(LOG001,"Myfun() is called"); 将在调用 myfun 的同一线程中执行(即在您的示例中的测试应用程序的主线程中)。为了在线程 logger_.Info 中调用 t,它必须移动到 threadfunction