Search code examples
c++operator-overloadinggoogletest

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


I am using following example from here

Consider I have following 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;            
  }
};

I am using Gtest to test this class.

But I could not find better way to test it.

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?

Thanks


Solution

  • Is there any way I can use EXPECT_EQ instead?

    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() );
    }
    

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