Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use enum classes with Boost Test

I have an enum class that I would like to use in my unit tests:

enum class MyEnumClass
{
    MyEntryA,
    MyEntryB
};

I would like to use it as follows:

MyEnumClass myEnumValue = MyEnumClass::MyEntryA;
BOOST_CHECK_EQUAL(myEnumValue, MyEnumClass::MyEntryB);

But I get this error, clearly because boost test is trying to output the value:

include/boost/test/test_tools.hpp:326:14: error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'
         ostr << t; // by default print the value
              ^

Adding ugly static_cast "solves" the problem:

BOOST_CHECK_EQUAL(static_cast<int>(myEnumValue), static_cast<int>(MyEnumClass::MyEntryB));

But I would like to avoid doing that for every enum class. I would also like to avoid defining << stream operators for every enum class.

Is there a simpler way to use enum classes with boost test?

Or do other unit test frameworks have a better way to deal with enum classes?

like image 967
ValarDohaeris Avatar asked Jun 16 '15 06:06

ValarDohaeris


3 Answers

Another solution is to use BOOST_CHECK(myEnumValue == MyEnumClass::MyEntryB), instead of BOOST_CHECK_EQUAL. This works for me, I'm assuming that for a simple true/false check, boost doesn't need to print out the enum class.

like image 156
jbcolli2 Avatar answered Nov 20 '22 11:11

jbcolli2


Solution:

enum class MyEnumClass {
  MyEntryA,
  MyEntryB
};

MyEnumClass myEnumValue = MyEnumClass::MyEntryA;
BOOST_TEST((myEnumValue == MyEnumClass::MyEntryA)); // Note extra pair of brackets
BOOST_TEST((myEnumValue == MyEnumClass::MyEntryB)); // Note extra pair of brackets

Results:

info: check (myEnumValue == MyEnumClass::MyEntryA) has passed
error: in "Suite/Test": check (myEnumValue == MyEnumClass::MyEntryB) has failed

Details:

  1. Use BOOST_TEST() as a test universal macro (Assertion Boost Test Universal Macro):

    • BOOST_TEST // or BOOST_TEST_CHECK
    • BOOST_TEST_REQUIRE
    • BOOST_TEST_WARN
  2. It seems that scoped enums (enum classes) should be added to Limitations and workaround that needs an extra pair of brackets.

like image 20
pandreidoru Avatar answered Nov 20 '22 12:11

pandreidoru


You can disable printing of the type in question with BOOST_TEST_DONT_PRINT_LOG_VALUE(). From the Boost docs:

typedef std::pair<int,float> pair_type;

BOOST_TEST_DONT_PRINT_LOG_VALUE( pair_type )

In this case should you get a mismatch, the test error message will tell you, but it but won't print the actual differing values.

like image 3
Malvineous Avatar answered Nov 20 '22 12:11

Malvineous