2010-12-02 86 views
3

我想單元測試客戶端/服務器功能。客戶端調用服務器,服務器調用回調函數。例如:如何測試回撥函數? (C++ 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()。有一個更好的方法嗎?

回答

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

你可能想說'BOOST_CHECK_MESSAGE(callbackCalled,「服務器沒有在指定的時間限制內調用CallBack()。」)`而不是4行? – kizzx2 2010-12-09 15:24:45