如何用gmock实现阻塞mock功能?

How to implement blocking mock function with gmock?

在我的项目中,我需要模拟一个在线程上运行的阻塞函数,我需要它在使用我的控件进行测试期间几次释放线程,根据我的命令,我希望它在大部分时间被阻塞读取函数在 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)。

Note: I wanted to use std::semaphore but it is available only on c++20 so I used semaphore.h insted, there some other implementation for cpp semaphore avallible if needed: 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;
};