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:
std::stringstream
variable 'ss' without calling ss.str("");ss.clear();
again and again ORoperator<<
using googletest.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
}