簡體   English   中英

我們可以在 C++ 中使用 Google Test/Gmock 模擬調用 std::thread 函數的函數嗎?

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

我可以模擬調用 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.問題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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM