0

I've overloaded operator<< like this:

std::ostream& operator<<(std::ostream& os, SomeClass C){ 
//SomeClass is the class to be represented with operator overloading
os << "{ ";
os << C.getPropertyA() << " ";
os << C.getPropertyB() << " }";
//getPropertyA(), getPropertyB():functions of 'SomeClass' that return std::string
return os;
}

Now I'm using googletest to test operator<< overloading like this:

SomeClass C1;
SomeClass C2;
.
.
std::stringstream ss;
std::string str;

//First test
ss << C1;
std::getline(ss, str);
EXPECT_EQ("<some expected value>", str); // googletest test

//Second test
ss.str("");ss.clear(); //Mandatory if 'ss' need to be reused
ss << C2;
std::getline(ss, str);
EXPECT_EQ("<some expected value>", str); // googletest test
.
.
//Some more use 'ss' follows

Now the problem is everytime I add a new test I need to add ss.str("");ss.clear(); before the test, apparently to empty stream and clear error state. This repetitive call of two std::stringstream functions makes me think I'm doing something wrong.

Hence I primarily need help with:

  • How to reuse std::stringstream variable 'ss' without calling ss.str("");ss.clear(); again and again OR
  • Best alternative to implement test for overloaded operator<< using googletest.
Jonas
  • 6,915
  • 8
  • 35
  • 53
MasterJEET
  • 349
  • 3
  • 14
  • You don't need to call both str() and clear(). Both calls do the same thing. Or or the other is enough for what you want to do. I don't think using a separate stringstream variable will bring any readability to your code. using either str("") or clear() (my personal choice) makes yuour intent quite clear, and is more efficient that creating a new stringstream from scratch. – Michaël Roy Jun 20 '17 at 21:41
  • @MichaëlRoy [Here](https://stackoverflow.com/questions/12112259/how-to-reuse-stringstream) the accepted answer says there's a need to call clear() even after calling str(""). For me using only str("") is working fine though. – MasterJEET Jun 23 '17 at 12:13
  • @MichaëlRoy Also using only `clear()` is not working. – MasterJEET Jun 23 '17 at 12:56

1 Answers1

5

You don't need to getline from string stream either as you can access underlying storage directly. The simpler approach would be to create new stringstream for each test:

//First test
{
    SomeClass C1;
    .
    std::stringstream ss;
    ss << C1;
    EXPECT_EQ("<some expected value>", ss.str()); // googletest test
}

//Second test
{
    SomeClass C2;
    .
    std::stringstream ss;
    ss << C2;
    EXPECT_EQ("<some expected value>", ss.str()); // googletest test
}
myaut
  • 11,174
  • 2
  • 30
  • 62
  • Thanks for pointing out redundant use of `getline()`. I'm sticking with @MichaëlRoy 's suggestion for now. – MasterJEET Jun 23 '17 at 12:24