Search code examples
c++equalsassertcppunit

C++ CPPUNIT_ASSERT with two parameters


In some code i found the following line:

CPPUNIT_ASSERT(1, val.getBytefield().size());

Does this really compare the two parameters for equality? Normally, i would expect this comparison with CPPUNIT_ASSERT_EQUAL:

CPPUNIT_ASSERT_EQUAL(1, val.getBytefield().size());

The test compiles and the assertion works in case 1, but not in case 2. Where is the difference?


Solution

  • It seems like you are using a compiler has an extension, which accepts 2 parameters to a single argument macro. I guess it's MSVC, see this

    Hence, the macro will check if the first argument is true or not, in your case, it's 1, which is contextual converted to the bool value true, by this expansion

    #define CPPUNIT_ASSERT(C) \
    ( CPPUNIT_NS::Asserter::failIf( !(C),                                   \
                                     CPPUNIT_NS::Message( "assertion failed",         \
                                                          "Expression: " #C), \
                                     CPPUNIT_SOURCELINE() ) )
    

    You can double check my statement by change:

    CPPUNIT_ASSERT(1, val.getBytefield().size());
    

    with:

    CPPUNIT_ASSERT(1000, val.getBytefield().size());
    

    CPPUNIT_ASSERT_EQUAL(1, val.getBytefield().size());
    

    From my experiment, .size() will likely return a std::size_t. From the definition of CPPUNIT_ASSERT_EQUAL:

    #define CPPUNIT_ASSERT_EQUAL(expected,actual) \
                    (assertEquals((expected),          \
                              (actual),                \
                              CPPUNIT_SOURCELINE(),    \
                              "" ) )
    

    and assertEquals:

    template<class T>
    void assertEquals   (   const T &   expected,
        const T &   actual,
        SourceLine  sourceLine,
        const std::string &     message
    )   
    

    Because type of 1 (int) and return type of .size() (std::size_t) is different, then no matching function can be found, the compiler can not compile your code.


    I think this is the solution:

    CPPUNIT_ASSERT(1 == val.getBytefield().size());
    CPPUNIT_ASSERT_EQUAL(std::size_t(1), val.getBytefield().size());