An operation will trigger another thread to call an expected fn(). Is that possible that main thread wait until the expectation meet?
EXPECT_CALL(mockObj, fn()).Times(1); // operation will trigger this call in another thread
operation();
WAIT_UNTIL_MOCK_MEET(mockObj); // is this possible?
operation_after_fn_called();
2
You can do it easily with gmock action and standard synchronization mechanisms. E.g. you can flip a boolean flag and notify a condition variable whenever your mock function is called:
class MyMock {
public:
MOCK_METHOD(void, fn, (), ());
};
constexpr auto TESTING_TIMEOUT = std::chrono::seconds(1);
TEST(xxx, yyy) {
bool calledFlag = false;
std::mutex m;
std::condition_variable cv;
MyMock mockObj;
EXPECT_CALL(mockObj, fn()).Times(1).WillOnce([&]() {
std::lock_guard lk(m);
calledFlag = true;
cv.notify_one();
});
auto fut = std::async(std::launch::async, [&]() { mockObj.fn(); });
{ // note the new scope to unlock the mutex when we finish waiting
std::unique_lock l(m);
ASSERT_TRUE(cv.wait_for(l, TESTING_TIMEOUT, [&]() { return calledFlag; }));
}
// operation_after_fn_called();
}
I prefer to use wait_for
version with timeout to avoid having tests that can block forever.
There is also Mock::VerifyAndClearExpectations(mockObj);
that you can use to force expectations check before the mock object is destroyed, e.g. if at that point in test you need to verify if fn
was not called too many times.