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

标签 c++ operator-overloading googletest

我正在使用来自 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 来测试这个类。

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

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

谢谢

最佳答案

Is there any way I can use EXPECT_EQ instead?

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

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相反。

关于c++ - 如何在 C++ Gtest 中测试输入和输出重载运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31815230/

相关文章:

c++ - 运行 make 时附加编译器标志

C++ 重载 : switching from friend to member function

python - Python 运算符重载到底是如何工作的?

c++ - 为什么 EXPECT_EQ 不能正确接受方法的结果作为参数?

c++ - 模拟整个图书馆

c++ - 如何在具有多个测试 .cpps 的头文件中使用 INSTANTIATE_TEST_CASE_P?

c++ - 将 typedef 与模板一起使用

c++ - 从反向迭代器获取 vector 中的索引

c++ - 如何将数据(Qt::UserRole)设置到 QSqlQueryModel 列中?

c++ - 运算符 << 重载错误 - 未找到运算符