通过谷歌测试测试异步调用
Test asynchronous call via google tests
我有一个类通信器,用于测试它是否可以连接测试服务器。我是这样称呼它的:
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
相关文章:
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 尽管测试成功,CppUnit测试核心仍被丢弃.为什么
- 数据成员SFINAE的C++17测试:gcc vs clang
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么二进制搜索在我的测试中不起作用
- 从父数组测试用例构造二叉树失败
- 试图对缓存进行跨步测试,但程序并没有结束
- 有什么好的方法可以让系统调用代理允许在单元测试中进行模拟
- OpenGL在启用深度测试时不会丢弃我的碎片
- 为测试目标创建具有不同源文件夹的文件
- 在子目录中使用target_sources()命令时用于单元测试(qtest)的项目结构
- VC++本机单元测试,找不到调试符号
- 使用 std::chrono::steady_clock 对线程/异步中的代码进行基准测试
- 通过谷歌测试测试异步调用
- 如何测试异步代码
- 在异步模式下使用ReadFile测试readbytes是否等于toread字节
- Googletest:如何异步运行测试
- 如何测试阻塞与异步