Search code examples
c++cppunit

Printf-Style Assertions using CPPUnit


Does CPPUnit have any functionality that would allow me to do printf-style assertions? For example:

CPPUNIT_ASSERT("Actual size: %d", p->GetSize(), p->GetSize() == 0);

I know this is not a valid CPPUNIT_ASSERT - I am just using this as an example.

I found CPPUNIT_ASSERT_MESSAGE(message,condition) which takes a string and then the condition to evaluate but no luck getting the value into the assert.


Solution

  • You should be able to do something like this:

    #define CPPUNIT_ASSERT_STREAM(MSG, CONDITION) \
        do { \
            std::ostringstream oss; \
            CPPUNIT_ASSERT_MESSAGE(\
                static_cast<std::ostringstream &>(oss << MSG).str(), \
                CONDITION); \
        } while (0)
    
    CPPUNIT_ASSERT_STREAM("Actual size: " << p->GetSize(), p->GetSize() == 0);
    

    The above macro can also be combined with Boost.format:

    CPPUNIT_ASSERT_STREAM(boost::format("Actual size: %d") % p->GetSize(),
                          p->GetSize() == 0);