Search code examples
c++googletest

google test PrintTo for std::set<std::string>


In the google test Advanced documentation they say to write PrintTo in the same namespace that defines the value to be printed, which is great if it's your own class in your own namespace, but if it's std::set you aren't supposed to add new members to namespace std.

So how do you customize the PrintTo behavior for std::set<std::string>? The default printer in google test stops printing after a certain number of values which isn't useful when the values that differ come after the ones emitted by the default printer.

#include <set>
#include <string>
#include <gtest/gtest.h>

void PrintTo(const std::set<std::string> &value, std::ostream *str)
{
    *str << "Got here!\n";
}

TEST(MapPrint, custom_printer)
{
    std::set<std::string> one{"foo"};
    std::set<std::string> two{"bar"};

    ASSERT_EQ(one, two); // doesn't print 'Got here!'
}

Solution

  • What works is to define PrintTo in namespace testing::internal. This still feels a little dirty to me. Presumably the internal namespace is so that google test can change whatever implementation details they like in there without regard to backwards compatibility. At least it doesn't result in undefined behavior as would defining PrintTo in namespace std.