Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost test case for function taking user input

Tags:

c++

boost-test

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?

like image 601
oadams Avatar asked Mar 07 '11 23:03

oadams


1 Answers

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.

like image 196
Daniel Trebbien Avatar answered Sep 30 '22 00:09

Daniel Trebbien