0

I am running a test where a usb device is opened, a packet is sent and received and it is closed again. It looks like this:

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

Now whenever there is an error in the receiveData() call and the Check for '5' fails, the closeDevice() and uninitDevice() are not called anymore and I cannot use the device in the next test. Is there a way to handle this? Maybe catch an exception and close and uninit the device in that catch scope too? Or is this a complete wrong approach? I am pretty new to unit testing. So any help is appreciated. Thanks!

4

3 に答える 3

2

initDevice / uninitDevice と openDevice/closeDevice を結び付けるために、最新の C++ の重要な概念の 1 つであるRAIIを使用します。

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で与えられた例に基づいています。

于 2013-10-10T14:18:32.957 に答える