4

The main reason for this question is that I want to test my operator overloader without having to do user input during my unit tests. How would I best achieve this?

std :: istream & operator>>( istream &in, Fruit & f )
{
   char temp[31];

   in >> temp;
   f.name = new char[strlen(temp) + 1];
   strcpy(f.name, temp);
   for( int i = 0; i < CODE_LEN; i++ ) 
      in >> f.code[i];
   return in;
}


std :: ostream & operator<<( ostream &out, const Fruit & f )
{ 
   out << setiosflags(ios::left) << setw(MAX_NAME_LEN) << f.name 
      << " ";
   for( int i = 0; i < CODE_LEN; i++ ) // why is this necessary?
      out << f.code[i];
   return out;
}
szymmirr
  • 27
  • 7
Panda
  • 690
  • 1
  • 6
  • 19

1 Answers1

3

The one way I've found to do it is by using sstream.

void main()
{
   Fruit one;

   ostringstream out;
   istringstream in("Strawberry 4321");

   in >> one;
   out << one;
   if( out.str() == "Strawberry                     4321")
      cout << "Success";
}

ostringstream and istringstream are the best way I've found to using it so far. Here is a bit of debate about whether to use stringstream, ostringstream, or istringstream, if you are curious: What's the difference between istringstream, ostringstream and stringstream? / Why not use stringstream in every case? Please let me know if there is a better way to test scenarios like this, obviously besides using a testing framework. Thanks!

Community
  • 1
  • 1
Panda
  • 690
  • 1
  • 6
  • 19