通过谷歌测试测试异步调用

Test asynchronous call via google tests

本文关键字:测试 异步 调用 谷歌      更新时间:2023-10-16

我有一个类通信器,用于测试它是否可以连接测试服务器。我是这样称呼它的:

class CommunicatorTest
{
public:
    CommunicatorTest() {}
    bool doTest()
    {
        bool _success;
        Parameters params;
        Communicator communicator;
        communicator.connect(params, [this, &_success](bool success)
        {
            statusCode = errorCode;
            m_condition.notify_one();
        });
        std::unique_lock<std::mutex> uGuard(m_mutex);
        m_condition.wait(uGuard);
        return _success;
    }
private:
    std::mutex m_mutex;
    std::condition_variable m_condition;
};
bool communicatorTest()
{
    CommunicatorTest test;
    bool success = test.doTest();
    return success;
}
TEST(CommunicatorTest, test_eq)
{
    EXPECT_EQ(communicatorTest(), true);
}

我尝试使用 condition 和互斥锁使这段代码同步,但它失败了,日志只说测试正在运行并立即完成。

有没有办法使用谷歌测试从回调中测试成功变量?提前谢谢。

在这些情况下,最好的解决方案是创建一个模拟服务器行为的模拟。运行测试时,不应依赖(除非非常必要(外部状态。

测试可能会失败,因为服务器未连接,没有互联网连接或任何条件。

您可以使用像Google Mock这样的东西,现在是Google Test套件的一部分来模拟行为:

class MockServer : public Server  {
 public:
  MOCK_METHOD2(DoConnect, bool());
  ....
};

然后执行以下操作:

TEST(ServerTest, CanConnect) {
  MockServer s;                          
  EXPECT_CALL(s, DoConnect())              
      ..WillOnce(Return(true));
  EXPECT_TRUE(server.isConnected());
}     

您可以模拟错误处理:

TEST(ServerTest, CannotConnect) {
  MockServer s;                          
  EXPECT_CALL(s, DoConnect())              
      ..WillOnce(Return(false));
  EXPECT_FALSE(server.isConnected());
  // ... Check the rest of your variables or states that may be false and
  // check that the error handler is working properly
}     

作为编写异步代码的人,我多次偶然发现这个问题 - 似乎大多数现有的C/C++测试框架都没有对测试异步代码的真正支持。主要需要的是一个事件循环,您可以在其中调度要执行的事情(模拟定时的外部事件等(,以及一种注册响应并选择性地检查它们发生的顺序的机制。因此,我没有尝试以某种方式采用现有的框架(这可能会导致更大的努力(,而是创建了自己的框架。我一直在使用它来测试我开发的类似 JavaScript 的 promise 类,它对我有好处。如果你有兴趣,我刚刚在GitHub上发布了它:https://github.com/alxvasilev/async-test