我正在尝试将std::chrono
类型用于Google测试。我的第一种方法是在命名空间PrintTo
中为nanoseconds
定义std::chrono
,但不幸的是it is undefined behavior to add declarations or definitions to namespace std
or to any namespace nested within std
。以下代码演示了该想法。
#include <gtest/gtest.h>
#include <chrono>
namespace std::chrono {
void PrintTo(nanoseconds ns, std::ostream* os) // UB
{
*os << ns.count() << " nanoseconds ";
}
}
namespace {
struct MyTest : ::testing::Test{
};
TEST_F(MyTest, PrintingTest)
{
using namespace testing;
using namespace std::chrono_literals;
ASSERT_THAT(1ns, Eq(2ns));
}
}
如果定义了std::chrono::PrintTo
,它将打印:
Value of: 1ns
Expected: is equal to 2 nanoseconds
Actual:
如果未定义std::chrono::PrintTo
,它将通过默认的字节打印机进行打印:
Value of: 1ns
Expected: is equal to 8-byte object <02-00 00-00 00-00 00-00>
Actual:
用Google测试为std::chrono
类型定义打印机的惯用方式是什么?
答案 0 :(得分:1)
您可以按如下所示重载chrono类型的std :: ostream运算符:
#include <gtest/gtest.h>
#include <chrono>
std::ostream& operator<<(std::ostream& os, const ::std::chrono::nanoseconds& ns)
{
return os << ns.count() << " nanoseconds ";
}
namespace {
struct MyTest : ::testing::Test{
};
TEST_F(MyTest, PrintingTest)
{
using namespace testing;
using namespace std::chrono_literals;
ASSERT_EQ(1ns, 2ns);
}
}
输出应符合预期:
error: Expected: 1ns
Which is: 1 nanoseconds
To be equal to: 2ns
Which is: 2 nanoseconds
[ FAILED ] MyTest.PrintingTest (0 ms)