Question

I overloaded the left shift operator in my class and the output works fine, so for example when I have a line which says cout << obj; I will output the fields seperated by a comma.

 ostream& operator<<(ostream& output, const MyClass& obj)
 {
     output << obj.field1 << ", " << obj.field2;
     return output;
 }

I want to write a test case for this operation, but I have no idea how to compare the returned result with the expected result in cxxtest. I tried the following, but it did not work:

 TS_ASSERT_EQUALS(cout << "1, 50.0", cout << obj);

Am I supposed to use a different cxxtest operation or change the parameter passing mechanism in TS_ASSERT_EQUALS?

Note that when I output the following lines, I get the same results:

 cout << obj;
 cout << "1, 50.0";

Note: I get a bunch of compiler errors when I attempt to compile the program because TS_ASSERT_EQUALS fails.

Was it helpful?

Solution

Even if it did compile, you're basically comparing cout with itself ...

Try writing to two distinct std::stringstreams, extracting their string values, and comparing these.

If you also need to test ostream flags, define a comparison function and use TS_ASSERT_RELATION.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top