当前,我的单元测试使用QTest :: qWait(ms)为捕获DBUS信号和执行插槽提供足够的时间,以满足EXPECT_CALL测试。 我想删除等待,并使用std :: condition_variable和std :: mutex使GMock EXPECT_CALL等待呼叫。
使用在这里找到的信息:Expecting googlemock calls from another thread我得到了以下代码;
std::condition_variable cv;
std::mutex mu;
bool ready{false};
BatteryLevelEvent batteryFlatEvt(EventType::EVT_BATTERY_FLAT, 12,
"MockEvent");
// setting up the expected call on the DB
EXPECT_CALL(mock_db_, Insert(batteryFlatEvt.ToString()))
.Times(1)
.WillOnce(InvokeWithoutArgs([&]() {
std::lock_guard<std::mutex> lock(mu);
ready = true;
cv.notify_one();
}));
// send DBUS message to trigger the Insert(...) call on mock_db_
connection.send(batteryLevelEventSignal);
// QTest::qWait(1000); //<-- test passes with this!
// test fails after 5 seconds
std::unique_lock<std::mutex> lock(mu);
EXPECT_TRUE(
cv.wait_for(lock, std::chrono::seconds(5), [&ready] { return ready; }));
lock.unlock();
Mock::VerifyAndClearExpectations(&mock_db_);
我在dbus-monitor上看到的信号肯定已经发送了
感谢您的帮助。
使用;
C ++ 11,
Gtest Master分支
结果...
Actual function call count doesn't match EXPECT_CALL(mock_db_, Insert(batteryFlatEvt.ToString()))...
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] EventServiceTester.TestReceivingEventSignals (5002 ms)
使用QTest:qWait(ms)
[ OK ] EventServiceTester.TestReceivingEventSignals (1002 ms)