Reputation: 6638
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!
Upvotes: 0
Views: 308
Reputation: 1856
I would use one of the key concepts within modern C++, RAII, to help keep initDevice / uninitDevice and openDevice/closeDevice tied together:
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
This is based off the example given in Rule of Zero.
Upvotes: 2
Reputation: 19232
You might be better off doing things that must happen first in a fixture setup and tidying up in a tear down function. Obviously using OO with RAII and putting the receiveData
as a class method would avoid this.
Alternatively, BOOST_CHECK
will check the condition and continue the test if it fails which would avoid the problem you have wherein BOOST_REQUIRE
stops the rest of the test executing.
Upvotes: 1
Reputation: 249133
You should use BOOST_CHECK
and BOOST_CHECK_EQUAL
when you want to report a condition not being satisfied, yet still continue the test. In this case, perhaps the first two items should be "REQUIRE"d, and the last three should be "CHECK"ed.
Upvotes: 1