gpt4 book ai didi

c++ - 通过谷歌测试测试异步调用

转载 作者:行者123 更新时间:2023-11-30 04:49:18 31 4
gpt4 key购买 nike

我有一个 Communicator 类,用于测试它是否可以连接到测试服务器。我是这样调用它的:

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);
}

我尝试使用条件和互斥使这段代码同步,但它失败了,日志仅显示测试正在运行并立即完成。

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

最佳答案

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

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

你可以使用类似 Google Mock 的东西,现在是用于模拟行为的 Google 测试套件的一部分:

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++ - 通过谷歌测试测试异步调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55478455/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com