我尝试在google test中使用std::chrono
类型。我的第一个方法是在命名空间std::chrono
中为nanoseconds
定义PrintTo
,但不幸的是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 test定义std::chrono
类型打印机的惯用方法是什么?
1条答案
按热度按时间q3qa4bjr1#
您可以为计时类型重载std::ostream运算符,如下所示:
然后,输出应如预期: