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

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

本文关键字:std lt string gt set PrintTo for google test      更新时间:2023-10-16

在谷歌测试高级文档中,他们说在定义要打印的值的同一命名空间中编写PrintTo,如果它是您自己的命名空间中的您自己的类,那就太好了,但如果它是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命名空间是为了让谷歌测试可以更改他们喜欢的任何实现细节,而不考虑向后兼容性。 至少它不会导致未定义的行为,就像在命名空间std中定义PrintTo一样。