简体   繁体   English

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

[英]Can we mock the function that calls std::thread function using Google Test/Gmock in C++?

Can I mock the function that calls std::thread function.我可以模拟调用 std::thread 函数的函数吗?

eg Creating thread:例如创建线程:

std::thread thread_id

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

Joining a thread in another function在另一个函数中加入一个线程

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

in test part:在测试部分:

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

I want to test this function but I am getting errors "terminate called without an active exception."我想测试这个函数,但我收到错误“在没有活动异常的情况下终止调用”。 That means the thread is created and became out of scope and testing is terminated.这意味着线程被创建并超出范围并且测试终止。 :( :(

Is it possible to use std::thread in gmock?是否可以在 gmock 中使用 std::thread?

I also read that pthread is used in multi-threading Google test from documentation at:我还从以下文档中了解到 pthread 用于多线程 Google 测试:

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

Please help with this.请帮忙解决这个问题。

There's no problem with setting expect calls on a mock that is used in a separate thread.在单独线程中使用的模拟上设置期望调用没有问题。 Your problem with terminate called without an active exception.您在terminate called without an active exception.问题terminate called without an active exception. is that you've created a thread that is never joined.是您创建了一个从未加入的线程。 Try:尝试:

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

But be aware that logger_.Info(LOG001, "Myfun() is called");但请注意logger_.Info(LOG001, "Myfun() is called"); will be executed in the same thread in which myfun is called (ie in the main thread of the test app in your example).将在调用myfun的同一线程中执行(即在示例中的测试应用程序的主线程中)。 In order to logger_.Info to be called in thread t , it must be moved to threadfunction .为了在线程t调用logger_.Info ,它必须移动到threadfunction

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM