在我的项目中,我需要模拟一个在线程上运行的阻塞函数,我需要它在测试期间用我的控件释放线程几次,在我的命令中,我希望它大部分时间都被阻塞,因为read func在while循环中。
class BlockFuncsIf {
public:
virtual bool Write(const Msg& msg) = 0;
virtual bool Read(Msg* msg) = 0;
};
class BlockFuncs: public BlockFuncsIf {
public:
MOCK_METHOD1(Write, bool(const Msg&));
MOCK_METHOD1(Read, bool(Msg* msg));
};
class TestedClass {
public:
MSG msg;
std::condition_variable cv;
bool success;
...
bool expectRead() {
success = true;
while(success) {
success = Read(&msg);
cv.notify_all();
}
}
...
};
我找到的解决方案是包装模拟函数并添加一个信号量来控制阻塞。在这个解决方案中,我从测试中控制信号量(sem_init,sem_post(。
注意:我想使用
std::semaphore
,但它只在c++20
上可用,所以我使用了指示的semaphore.h
,如果需要的话,还有一些其他的cpp信号量实现:cpp信号灯实现。
class BlockFuncsIf {
public:
virtual bool Write(const Msg& msg) = 0;
virtual bool Read(Msg* msg) = 0;
};
class BlockFuncsMock: public BlockFuncsIf {
public:
MOCK_METHOD1(Write, bool(const Msg&));
MOCK_METHOD1(Read, bool(Msg* msg));
static std::shared_ptr<BlockFuncsMock> _blockFuncsMockObj;
};
std::shared_ptr<BlockFuncsMock> BlockFuncsMock::_blockFuncsMockObj = std::make_shared< BlockFuncsMock >();
class BlockFuncs {
public:
bool Write(const Msg& msg){
sem_wait(&SemWriteMutex);
return BlockFuncsMock::_blockFuncsMockObj->Write(msg);
}
bool Read(Msg* msg){
sem_wait(&SemReadMutex);
return BlockFuncsMock::_blockFuncsMockObj->Read(msg);
}
sem_t SemWriteMutex;
sem_t SemReadMutex;
};