【问题标题】:Can we mock the function that calls std::thread function using Google Test/Gmock in C++?我们可以在 C++ 中使用 Google Test/Gmock 模拟调用 std::thread 函数的函数吗?
【发布时间】:2021-09-21 08:18:46
【问题描述】:

我可以模拟调用 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

请帮忙。

【问题讨论】:

    标签: c++ multithreading stdthread gmock


    【解决方案1】:

    在单独线程中使用的模拟上设置期望调用没有问题。您对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 的同一线程中执行(即在您的示例中的测试应用程序的主线程中)。为了在线程t 中调用logger_.Info,必须将其移动到threadfunction

    【讨论】:

    • 编辑了问题。我有线程连接,但在另一个函数中。因此不能在同一个函数中添加 t.join()。
    • threadfunction 在做什么?没有全貌就很难提供帮助。你能创建reprex (stackoverflow.com/help/minimal-reproducible-example)吗?
    猜你喜欢
    • 1970-01-01
    • 2010-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    • 2018-03-04
    相关资源
    最近更新 更多