如何在C ++ Gtest中测试输入和输出重载运算符 [英] How to test input and output overloaded operator in C++ Gtest

查看:128
本文介绍了如何在C ++ Gtest中测试输入和输出重载运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此处

考虑我有以下课程

#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来测试此类.

I am using Gtest to test this class.

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

But I could not find better way to test it.

我可以使用gtest ASSERT_NO_THROW中提供的宏,但不会验证值. 有什么方法可以代替我使用EXPECT_EQ?

I can use the macro provided in gtest ASSERT_NO_THROW, but it will not validate the values. Is there any way I can use EXPECT_EQ instead?

谢谢

推荐答案

有什么方法可以代替我使用EXPECT_EQ?

Is there any way I can use EXPECT_EQ instead?

您可以使用stringstreamoperator<<的结果打印为字符串,然后比较该字符串.

You can use a stringstream to print the results of operator<< to a string, then compare the string.

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.

Input test would be similar, just use std::istringtream instead.

这篇关于如何在C ++ Gtest中测试输入和输出重载运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆