{fmt} 等于 cout.rdbuf?

{fmt} equivalent to cout.rdbuf?

我有一个通过读取函数发送的缓冲区来验证函数的单元测试:

template <typename Manifold>
void print_manifold(Manifold const& manifold)
try
{
  std::cout << "Manifold has " << manifold.N0() << " vertices and "
            << manifold.N1() << " edges and " << manifold.N2() << " faces and "
            << manifold.N3() << " simplices.\n";
  // fmt::print(
  //    "Manifold has {} vertices and {} edges and {} faces and {}
  //    simplices.\n", manifold.N0(), manifold.N1(), manifold.N2(),
  //    manifold.N3());
}
catch (...)
{
  std::cerr << "print_manifold() went wrong ...\n";
  throw;
}  // print_manifold

并且:

SCENARIO("Printing results", "[utility]")
{
  // redirect std::cout
  stringstream buffer;
  cout.rdbuf(buffer.rdbuf());
  GIVEN("A Manifold3")
  {
    Manifold3 const manifold(640, 4);
    WHEN("We want to print statistics on a manifold.")
    {
      THEN("Statistics are successfully printed.")
      {
        print_manifold(manifold);
        CHECK_THAT(buffer.str(), Catch::Contains("Manifold has"));
      }
    }
}

有没有办法捕获 fmt::printstdout 生成的输出?

当我注释掉 cout 代码并取消注释 fmt 代码时,我得到了之前 cout <<.

实例生成的缓冲区

这更像是一个 C stdio 而不是 {fmt} 问题,但您可以将 stdout 重定向到一个管道并从中读取输出,如 Redirecting stdout to pipe in C 的答案中所述。这不是一个很好的单元测试,因为它取决于全局状态,但您当前的测试有同样的问题。