I am creating a test for a function which gets the user input with std::cin
, and then returns it. The test just needs to check if the input from the user, is the one actually returned.
Problem is, the test should be automated so I can't manually react to the std::cin
prompt. What can I do to set the input with code?
Asked
Active
Viewed 113 times
1

Schweini
- 25
- 6
-
4Redirect input from a file. `myprogram < input.txt` – Retired Ninja Oct 01 '22 at 17:53
-
Do you know what OS these tests are going to be run on? If it's a POSIX system, then you can redirect the standard input/output file handles to mock input and output. See [this question](https://stackoverflow.com/questions/37385560/c-redirect-or-disable-stdio-temporarily), which is for redirecting stdout but could be easily adapted to redirect stdin instead. – Silvio Mayolo Oct 01 '22 at 18:00
1 Answers
2
I wouldn't bother with automation or redirection of the std::cin
functionality.
From personal experience it always get much more complicated than it has to be.
A good approach would be to separate your behavior.
Bad:
void MyFunction()
{
std::string a;
std::cin >> a;
auto isValid = a.size() > 1;
}
Better:
bool ValidateInput(const std::string& myString)
{
return myString.size() > 1;
}
void MyFunction()
{
std::string a;
std::cin >> a;
auto isValid = ValidateInput(a);
}
There are more complex solutions to this with std::cin.rdbuf
.
You could adjust rdbuf - use this only if you don't have control on the function
.
For example:
#include <sstream>
#include <iostream>
void MyFunc()
{
std::string a;
std::cin >> a;
auto isValid = a.size() > 1;
if (isValid)
{
std::cout << a;
}
}
int main()
{
std::stringstream s;
s << "Hello_World";
std::cin.rdbuf(s.rdbuf());
MyFunc();
}
Always separate the input functions from the validation functions and the processing functions.
Best of luck!

SimplyCode
- 318
- 2
- 9
-
-
1@RetiredNinja Thanks, I wrote pseudo code and forgot to fix that :) – SimplyCode Oct 02 '22 at 06:32