c++ 如何打印标准::计时类型与谷歌测试?

qqrboqgw  于 2022-12-05  发布在  其他
关注(0)|答案(1)|浏览(133)

我尝试在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类型打印机的惯用方法是什么?

q3qa4bjr

q3qa4bjr1#

您可以为计时类型重载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)

相关问题