gpt4 book ai didi

unit-testing - 如何对回调函数进行单元测试? (C++ boost 单元测试)

转载 作者:行者123 更新时间:2023-12-04 05:27:54 25 4
gpt4 key购买 nike

我想对客户端/服务器功能进行单元测试。客户端调用服务器,服务器调用回调函数。像这样的东西:

void CallBack()
{
BOOST_SUCCESS(); // test is successful if this is called
}

BOOST_AUTO_TEST_CASE( ConnectionTest_ClientCallback )
{
CallServer(); // server will do work and call CallBack()
sleep(20);
BOOST_FAIL("Server hasn't called CallBack() within specified time limit.");
}

但是上面的方法不起作用,因为在任何测试期间都可以调用 CallBack()。有更好的方法吗?

最佳答案

在回调函数中设置一个变量:

void CallBack()
{
callBackCalled = true;
}

并在测试中测试:

BOOST_AUTO_TEST_CASE( ConnectionTest_ClientCallback )
{
callbackCalled = false;
CallServer(); // server will do work and call CallBack()
sleep(20);
if (callbackCalled)
BOOST_SUCCESS();
else
BOOST_FAIL("Server hasn't called CallBack() within specified time limit.");
}

编辑:kizzx2 建议的更好的解决方案:

BOOST_AUTO_TEST_CASE( ConnectionTest_ClientCallback )
{
callbackCalled = false;
CallServer(); // server will do work and call CallBack()
sleep(20);
BOOST_CHECK_MESSAGE(callbackCalled, "Server hasn't called CallBack() within specified time limit.");
}

关于unit-testing - 如何对回调函数进行单元测试? (C++ boost 单元测试),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4331849/

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