Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to fake user input in C

Tags:

c

input

testing

Simple question I hope. I have a function that keeps prompting for user input (characters) and returns a character once it finds that the input is valid under certain conditions. I'm writing tests for this and other similar functions, but don't know how to fake user input. By the way, I'm using scanf() to get user input.

like image 960
endmade Avatar asked Oct 14 '25 16:10

endmade


2 Answers

You can change the behaviour of standard input to read from a file with freopen. Place the test input in a file and call this before your test.

freopen("filename", "r", stdin);
like image 157
Tugrul Ates Avatar answered Oct 17 '25 10:10

Tugrul Ates


You can do something like

echo -e "Test string\nAnother string" | ./a.out

The string of echo command should be in the sequence which the program requires

cat test_str_file | ./a.out

The file test_str_file should contain the test strings in the sequence the program requires

On the other hand you can simply replace the code's input section with some dummy sections. If you have a separate module for input, then replace it with dummy.

like image 44
phoxis Avatar answered Oct 17 '25 08:10

phoxis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!