CPPUNIT_ASSERT_EQUAL on std::unique_ptr
Question
I want to test if my application returns a nullptr unique ptr. I have tried a few things but nothing get through the compiler. I hope someone has already tried and found a way to make this work. Some things i have tried:
std::unique_ptr<SomeClass> some_class_ptr;
CPPUNIT_ASSERT_EQUAL(std::unique_ptr<SomeClass>(), some_class_ptr);
gives: libcppunit/include/cppunit/TestAssert.h|49|error: no match for ‘operator<<’ in ‘ost << x’|
Inside TestAssert.h:
template <class T>
void assertEquals( const T& expected,
const T& actual,
SourceLine sourceLine,
const std::string &message )
{
if ( !assertion_traits<T>::equal(expected,actual) ) // lazy toString conversion...
{
Asserter::failNotEqual( assertion_traits<T>::toString(expected),
assertion_traits<T>::toString(actual),
sourceLine,
message );
}
}
CPPUNIT_ASSERT_EQUAL(nullptr, some_class_ptr);
gives: /tests/SomeTestClass.cpp|432|error: no matching function for call to ‘assertEquals(std::nullptr_t, std::unique_ptr&, CppUnit::SourceLine, const char [1])’|
CPPUNIT_ASSERT_EQUAL(nullptr, some_class_ptr.get());
gives: /tests/SomeTestClass.cpp|432|error: no matching function for call to ‘assertEquals(std::nullptr_t, std::unique_ptr::pointer, CppUnit::SourceLine, const char [1])’|
I think the first one should be the correct one but it is not compiling. Can anyone give me a correct construction for this ?
Solution
CPPUNIT_ASSERT_EQUAL
requires its arguments to be of exactly the same type. Since you don't need to be able to output a representation of the nullptr
argument, you can just use CPPUNIT_ASSERT
:
CPPUNIT_ASSERT(nullptr == some_class_ptr);
or
CPPUNIT_ASSERT(!some_class_ptr);
OTHER TIPS
The problem seems to be with CPPUNIT_ASSERT_EQUAL
, but I can't see any good reason to use that. I assume there is a CPPUNIT_ASSERT
or the like (check the documentation or sources). Then just write CPPUNIT_ASSERT( some_class_ptr().get() == 0 )
, or really any expression you prefer for checking pointer nullness.