5

I have a function that takes in user input via std::cin:

std::getline(std::cin, in);

and creates a corresponding data structure by matching it with a regular expression. The function then returns this data structure.

I'm using boost.test and I want to create a unit test to check that the output data type is correct given some inputs. However I don't know how to go about it since the input isn't passed as an argument to the function.

EDIT: Is there a simple way to create a boost test case that feeds the function a string via standard input?

oadams
  • 3,019
  • 6
  • 30
  • 53

1 Answers1

8

If you have access to the source code of the function that calls std::getline, then the easiest solution is to rewrite it as a wrapper of another function having the same signature and implementation, but taking an additional std::istream& parameter that is used in place of std::cin. For example, if you currently have:

my_struct my_func()
{
    //...

    std::getline(std::cin, in);

    //...
}

Then rewrite like this:

my_struct my_func(std::istream& is);

inline my_struct my_func()
{
    return my_func(std::cin);
}

my_struct my_func(std::istream& is)
{
    //...

    std::getline(is, in);

    //...
}

This way, you will be able to test the core functionality of my_func on constructed input sequences by passing std::istringstream objects into my_func(std::istream&).

If you do not have access to the source code of the function that calls std::getline, then one trick that you can use is to replace the standard in descriptor. See this answer for code that replaces the standard out descriptor and modify accordingly.

Community
  • 1
  • 1
Daniel Trebbien
  • 38,421
  • 18
  • 121
  • 193
  • might be a stupid question, but should the wrapper class have a different name to the wrappee class? – oadams Mar 08 '11 at 01:11
  • 1
    @oadams: I presume you mean wrapper *function* and wrapped *function*, correct? C++ supports [function overloading](http://msdn.microsoft.com/en-us/library/5dhe1hce%28VS.80%29.aspx), so there can be more than one function named `my_func`. – Daniel Trebbien Mar 08 '11 at 01:52
  • oh, ok. yeah, function - whoops. – oadams Mar 08 '11 at 02:09