如何在 C++ Gtest 中测试输入和输出重载运算符

How to test input and output overloaded operator in C++ Gtest

我正在使用 here

中的以下示例

考虑到我有关注 class

#include <iostream>

class Distance {
private:
  int feet;             
  int inches;           

public:
  Distance()             : feet(), inches() {}
  Distance(int f, int i) : feet(f), inches(i) {}

  friend std::ostream &operator<<( std::ostream &output, const Distance &D )
  { 
     output << "F : " << D.feet << " I : " << D.inches;
     return output;            
  }

  friend std::istream &operator>>( std::istream  &input, Distance &D )
  { 
     input >> D.feet >> D.inches;
     return input;            
  }
};

我正在使用 Gtest 来测试这个 class。

但我找不到更好的方法来测试它。

我可以使用 gtest ASSERT_NO_THROW 中提供的宏,但它不会验证值。 有什么办法可以改用 EXPECT_EQ 吗?

谢谢

Is there any way I can use EXPECT_EQ instead?

您可以使用stringstreamoperator<<的结果打印到一个字符串中,然后比较该字符串。

https://en.cppreference.com/w/cpp/io/basic_stringstream

TEST( Distance, Output )
{
    std::ostringstream out;
    Distance d;
    out << d;
    EXPECT_EQ( "F:0 I:0", out.str() );
}

输入测试类似,只需使用 std::istringtream 即可。

您想测试有关运算符的哪些内容?

  • 流在写入或读取后处于良好状态。
    你可以检查一下。

  • 输出运算符为特定距离写入特定字符串。
    您可以通过写入 std::ostringstream 并将调用其 str() 成员的结果与您的期望进行比较来完成此操作。

  • 输入迭代器从特定字符串读取特定距离。
    您可以使用用字符串初始化的 std::istringstream 来执行此操作,并将从中读取的距离与您的预期进行比较。

  • 那个class吃自己的狗粮
    使用std::stringstream写入,然后从中读取,并将读取的内容与写入的内容进行比较。
    注意:目前会失败。