Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare ptr with nullptr in gtest

Tags:

c++

googletest

Have some code:

EXPECT_NE(nullptr,ptr);

And I get the following compilation error:

'operator <<' is ambiguous

could be 'std::basic_ostream<char,std::char_traits<char>> &std::basic_ostream<char,std::char_traits<char>>::operator <<<void>(std::nullptr_t)'
or       'std::basic_ostream<char,std::char_traits<char>> &testing::internal2::operator <<<char,std::char_traits<char>,T>(std::basic_ostream<char,std::char_traits<char>> &,const T &)'

Could this be a library version problem?

like image 991
Игорь Пугачев Avatar asked Feb 13 '19 16:02

Игорь Пугачев


2 Answers

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 :)

like image 148
EmDroid Avatar answered Sep 25 '22 05:09

EmDroid


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

like image 36
Richard Hodges Avatar answered Sep 21 '22 05:09

Richard Hodges