google 为 std::set<std::string> 测试 PrintTo

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

在 google 测试 Advanced documentation 中,他们说要在定义要打印的值的同一个命名空间中写入 PrintTo,如果它是您自己的 class 在你自己的命名空间中,但如果它是 std::set 你不应该向命名空间 std.

添加新成员

那么如何为 std::set<std::string> 自定义 PrintTo 行为? google 测试中的默认打印机在一定数量的值后停止打印,当不同的值出现在默认打印机发出的值之后时,这没有用。

#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!'
}

有效的是在命名空间 testing::internal 中定义 PrintTo。这对我来说还是有点脏。据推测 internal 命名空间是为了 google test 可以更改他们喜欢的任何实现细节,而不考虑向后兼容性。至少它不会像在命名空间 std.

中定义 PrintTo 那样导致未定义的行为