簡體   English   中英

Boost Unit Test:捕獲一個不成功的測試

[英]Boost Unit Test: Catch an unsuccessful Test

我正在運行一個打開 USB 設備、發送和接收數據包並再次關閉的測試。 它看起來像這樣:

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

現在,只要在receiveData()調用中出現錯誤並且 Check for '5' 失敗, closeDevice()uninitDevice()就不再被調用,並且我無法在下一次測試中使用該設備。 有沒有辦法處理這個? 也許捕獲一個異常並關閉並取消該捕獲范圍內的設備? 或者這是一個完全錯誤的方法? 我對單元測試很陌生。 所以任何幫助表示贊賞。 謝謝!

我將使用現代 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

這是基於零規則中給出的示例。

當您想要報告不滿足條件但仍繼續測試時,您應該使用BOOST_CHECKBOOST_CHECK_EQUAL 在這種情況下,也許前兩項應該是“REQUIRE”d,后三項應該是“CHECK”。

您最好先做一些必須在夾具設置中發生的事情,然后在拆卸功能中進行整理。 顯然,使用帶有 RAII 的 OO 並將receiveData作為類方法可以避免這種情況。
或者, BOOST_CHECK將檢查條件並在測試失敗時繼續測試,這將避免您遇到的問題,即BOOST_REQUIRE會停止其余的測試執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM