feelfree
feelfree

Reputation: 11753

Is there a function in boost::test that can return error value?

Boost Test Library is a very useful unit test framework. However, one thing I feel uncomfortable is that during the unit test if errors happen it will inform the user but not the program itself. Let me make my point clear by using BOOST_CHECK as an example:

i=3;
j=4;
BOOST_CHECK(i==j);

The above test case will fail. So, checking the details to find why this test fails will be very interesting. In this case, printing some variables or performing more complicated operations such as writing a file to the disk in the program will be necessary if it knows that the unit test fails. However, BOOST_CHECK will not return a value to denote the test is successful or not. A perfect function should work like this:

    i=3;
    j=4;
    if(Enhanced_BOOST_CHECK(i==j) == failed)
    {

        // print some internal varaibles.
        // or write some data to a file in the disk
     }

So my question is: does BOOST Test Library support this functionality? Thanks.

Upvotes: 4

Views: 1549

Answers (2)

TobiMcNamobi
TobiMcNamobi

Reputation: 4813

Boost provides a macro BOOST_WARN_MESSAGE (and BOOST_CHECK_MESSAGE and BOOST_REQUIRE_MESSAGE as well). In your case it could be used like this:

i=3;
j=4;

bool isEqual = i==j;

BOOST_CHECK(isEqual);
BOOST_WARN_MESSAGE(isEqual, "Failure since i = " << i << " and j = " << j);

Further info is found here.

Upvotes: 3

Martin Ba
Martin Ba

Reputation: 38775

Boost Test offers a lot more than just BOOST_CHECK.

See the docs:

The UTF testing tools reference

BOOST_<level>
BOOST_<level>_BITWISE_EQUAL
BOOST_<level>_CLOSE
BOOST_<level>_CLOSE_FRACTION
BOOST_<level>_EQUAL
BOOST_<level>_EQUAL_COLLECTION
BOOST_<level>_EXCEPTION
BOOST_<level>_GE
BOOST_<level>_GT
BOOST_<level>_LE
BOOST_<level>_LT
BOOST_<level>_MESSAGE
BOOST_<level>_NE
BOOST_<level>_NO_THROW
BOOST_<level>_PREDICATE
BOOST_<level>_SMALL
BOOST_<level>_THROW
BOOST_ERROR
BOOST_FAIL
BOOST_IS_DEFINED

You may want to use BOOST_CHECK_EQUAL(i, j) in your case.

Alternatively, looking at your second example, for more complex cases, you simply can do:

if (!(i==j)) {
  // Complex condition failed - report to boost test and add custom message
  std::string message = ...;
  BOOST_CHECK_MESSAGE(false, message);
}

Upvotes: 1

Related Questions