How to put data in cin from string

c++, cin, unit-testing

Solution

Assuming you can control `main()` (or some other function called before the functions to be tested) you can change where `std::cin` reads from and where `std::cout` writes to:

int main(int ac, char* av[]) {
    std::streambuf* orig = std::cin.rdbuf();
    std::istringstream input("whatever");
    std::cin.rdbuf(input.rdbuf());
    // tests go here
    std::cin.rdbuf(orig);
}

(likewise for `std::cout`)

This example saves the original stream buffer of `std::cin` so it can be replaced before leaving `main()`. It then sets up `std::cin` to read from a string stream. It can be any other stream buffer as well.

Problem

I need to write tests(using google testing framework) for small study program that was written not by me. (it's just small console game which can get modes from command line or just get it in runtime) There is a problem: I can't change the souce code but there is in almost all methods used cout and cin. and my question is "how to answer on requests (cin) of programm while testing (something like get data for cin from string )?".

Original source