Compare ptr with nullptr in gtest
If you want to be more explicit, you could also use
EXPECT_TRUE(ptr != nullptr);
(that's what I normally do)
Btw. funnily enough, in my work project I still have to work with C++98 (still building for Sun and AIX, although it will soon go away) and I ended up creating my own NullPtrT
class and NullPtr
object in the common library, which actually works with gtest EXPECT_EQ
and EXPECT_NE
macros. So that I can do
EXPECT_NE(NullPtr, ptr);
I don't remember how exactly I made that work :)
I've run into the same problem recently with GTest 1.8.0, but only when using Visual Studio 2019 in C++17 mode. Visual Studio 2019 works fine in C++14 mode, and neither Clang nor GCC seem to have the same problem in C++17 mode.
The issue is that with C++17 there's a new overload in the standard library for the std::ostream::operator<<
that takes a nullptr_t
, but GTest also provides its own, so your compiler does not know which one to use.
If you have full control over your version of GTest then https://github.com/google/googletest/pull/1620/commits/f66ab00704cd47e4e63ef6d425ca14b9192aaebb is a change for GTest-1.8.0 that resolves the issue: It's not as easy as deleting the overload, because the function in question is a template whose other instantiations are still used. Instead, the solution is to define an explicit void PrintTo(std::nullptr_t, ::std::ostream* os)
function that will then automatically be used, no longer deferring to the ambiguous overloads.
When modifying GTest is not an option then the solutions mentioned in the other answers to not use EXPECT_EQ
/EXPECT_NE
when one parameter is a nullptr_t
are your best bet.
namespace {
template<class T>
auto not_nullptr(T*p) -> testing::AssertionResult
{
if (p)
return testing::AssertionSuccess();
else
return testing::AssertionFailure() << "pointer is null";
}
}
...
EXPECT_TRUE(not_nullptr(ptr));
reference:
https://github.com/google/googletest/blob/master/docs/advanced.md#using-a-function-that-returns-an-assertionresult