Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I unit test a console input class?

In one of my applications I have a class which is responsible for user input. The default method of input is the console (keyboard), and I want to write some unit tests for it to make sure it is correct.

I am considering using the google-test framework for my unit testing, which makes it easy to automate all the testing. However, I am not sure how I can automate testing of the console input.

Is there any way to simulate user input on the keyboard? Or do I have to manually enter my test input? Or perhaps redirect stdin (either in code or by a pipe when running the unit test)?

EDIT: I am planning on using GNU readline for user input. At the moment I can't see any way to redirect the input stream of this library - perhaps someone else has experience with this?

like image 599
a_m0d Avatar asked Jan 23 '23 07:01

a_m0d


2 Answers

You could use expect.

like image 80
chotchki Avatar answered Jan 25 '23 21:01

chotchki


Basically, your class should be able to use random input stream, not only stdin (and you have to refactor it, if it's unable yet).

After that you'll be able to simply put a mock stream with your custom data and to simulate any user input.

like image 21
Vanya Avatar answered Jan 25 '23 20:01

Vanya