2013-10-10 35 views
0

我正在運行一個測試,打開USB設備,發送並接收數據包並再次關閉。 它看起來像這樣:增強單元測試:抓取不成功的測試

void TestCase1(void) 
{ 
int recv; 
BOOST_REQUIRE(initDevice()); 
BOOST_REQUIRE(openDevice()); 
BOOST_REQUIRE_EQUAL(receiveData(), 5); 
BOOST_REQUIRE(closeDevice()); 
BOOST_REQUIRE(uninitDevice()); 
} 

現在每當有在receiveData()調用錯誤,並且檢查「5」出現故障,closeDevice()uninitDevice()不再被所謂的,我不能在接下來的測試中使用的設備。有沒有辦法解決這個問題?也許捕獲一個異常,並關閉和取消該設備在該捕獲範圍?或者這是一個完全錯誤的方法? 我對單元測試很新穎。所以,任何幫助表示讚賞。謝謝!

+0

是打開實際的USB端口在* unit *測試中做一個明智的事情? – doctorlove

回答

2

我會用現代C++,RAII中的關鍵概念之一,以幫助保持initDevice/uninitDevice和openDevice/closeDevice捆綁在一起:

class USBDeviceHandler 
{ 
public: 
    USBDeviceHandler() 
    : initDeviceHandle { ::initDevice()), &::uninitDevice }, 
     openDeviceHandle { ::openDevice()), &::closeDevice } 
    { 
    } 

    using init_handle = std::unique_ptr<void, decltype(&::uninitDevice)>; 
    using open_handle = std::unique_ptr<void, decltype(&::closeDevice)>; 

    init_handle initDeviceHandle; 
    open_handle openDeviceHandle; 
}; 

void TestCase1(void) 
{ 
int recv; 
USBDeviceHandler device; //init/open is called upon construction 
BOOST_REQUIRE_EQUAL(receiveData(), 5); 
}//close/uninit is called upon destruction 

這是基於關閉在Rule of Zero給出的例子。

+0

USBWrapper應該是USBDeviceHandler的構造函數嗎? – doctorlove

+0

@doctorlove - 哎呀,固定。通過寫答案,我改變了幫手類的名字。 –

1

當您想報告條件不滿意,但仍然繼續測試時,您應該使用BOOST_CHECKBOOST_CHECK_EQUAL。在這種情況下,前兩項應該是「REQUIRE」d,最後三項應該是「CHECK」。

1

你可能會做一些事情,這些事情必須首先發生在燈具設置中,然後整理一個拆卸功能。顯然,使用OII和RAII並將receiveData作爲類方法可以避免這種情況。
或者,BOOST_CHECK將檢查條件並在測試失敗時繼續測試,這樣可以避免其中BOOST_REQUIRE停止執行其餘測試的問題。