如何对回调函数进行单元测试? (C ++ Boost单元测试)

时间:2010-12-02 05:00:10

标签: unit-testing boost

我想单元测试客户端/服务器功能。客户端调用服务器,服务器调用回调函数。类似的东西:

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()。有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

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

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