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!

1
  • is opening actual usb ports a sensible thing to do in a unit test? Commented Oct 10, 2013 at 14:37

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Is USBWrapper supposed to be the constructor for USBDeviceHandler?
@doctorlove - oops, fixed. I changed the name of the helper class halfway through writing the answer.
1

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.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.