Search code examples
c++c++11operator-overloadinggoogleteststringstream

How to avoid use of std::stringstream.str() and std::stringstream.clear() while reusing std::stringstream variable?


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.

Solution

  • 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
    }