'How can I use member functions of google unit test case in thread defined in the unit test?
I have a google unit test where I've defined a few functions in it. It looks like the following
class MyUnitTest {
protected:
void SetUp() override;
void TearDown() override;
void MyFunction();
};
And I have a test case such as the following:
TEST_F(MyUnitTest, MyCustomTest)
{
std::thread t1(MainThreadFunction);
t1.join();
}
void MainThreadFunction()
{
MyFunction(); // <--- I cannot call this, as it is out of scope.
}
My question is, without making MyFunction a static function, there a way to call MyFunction within MainThreadFunction()? I tried std::bind as suggested here, but it didn't work for me:
Solution 1:[1]
I think the easiest solution would be to use a lambda instead of MainThreadFunction:
#include <gtest/gtest.h>
#include <iostream>
class MyUnitTest : public ::testing::Test {
protected:
void SetUp() override {}
void TearDown() override {}
void MyFunction() { std::cout << "\n***** MyFunction *****\n\n"; }
};
TEST_F(MyUnitTest, MyCustomTest) {
std::thread t1([this](){ this->MyFunction(); });
t1.join();
}
int main() {
::testing::InitGoogleTest();
[[maybe_unused]] auto i{ RUN_ALL_TESTS() };
}
In case you need to use MainThreadFunction, have it receive a pointer to a member function. Notice, in this case, I had to make MyFunction public:
#include <gtest/gtest.h>
#include <iostream>
class MyUnitTest : public ::testing::Test {
protected:
void SetUp() override {}
void TearDown() override {}
public:
void MyFunction() { std::cout << "\n***** MyFunction *****\n\n"; }
};
void MainThreadFunction(MyUnitTest* ut, void (MyUnitTest::*MyFunctionPtr)()) {
(ut->*MyFunctionPtr)();
}
TEST_F(MyUnitTest, MyCustomTest) {
std::thread t1(MainThreadFunction, this, &MyUnitTest::MyFunction);
t1.join();
}
int main() {
::testing::InitGoogleTest();
[[maybe_unused]] auto i{ RUN_ALL_TESTS() };
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
