在我的项目中,我需要模拟一个在线程上运行的阻塞函数,我需要它在测试期间使用我的控件多次释放线程,在我的命令中,我希望它在大部分时间被阻塞作为读取函数处于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
insted,如果需要,还有一些其他的 cpp 信号量实现:cpp semaphore implementation。
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;
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句