@@ -97,4 +97,49 @@ You can set the max number of times to ask in the ``$attempts`` argument.
97
97
If you reach this max number it will use the default value, which is given
98
98
in the last argument. Using ``false `` means the amount of attempts is infinite.
99
99
The user will be asked as long as he provides an invalid answer and will only
100
- be able to proceed if her input is valid.
100
+ be able to proceed if her input is valid.
101
+
102
+ Testing a command which expects input
103
+ -------------------------------------
104
+
105
+ If you want to write a unit test for a command which expects some kind of input
106
+ from the command line, you need to overwrite the HelperSet used by the command::
107
+
108
+ use Symfony\Component\Console\Helper\DialogHelper;
109
+ use Symfony\Component\Console\Helper\HelperSet;
110
+
111
+ // ...
112
+
113
+ public function testExecute()
114
+ {
115
+
116
+ // ..
117
+
118
+ $commandTester = new CommandTester($command);
119
+
120
+ $dialog = new DialogHelper();
121
+ $dialog->setInputStream($this->getInputStream('Test\n'));
122
+ // Equals to a user inputing "Test" and hitting ENTER
123
+ // If you need to enter a confirmation, "yes\n" will work
124
+
125
+ $command->setHelperSet(new HelperSet(array($dialog)));
126
+
127
+ $commandTester->execute(array('command' => $command->getName()));
128
+
129
+ // assert
130
+
131
+ }
132
+
133
+ protected function getInputStream($input)
134
+ {
135
+ $stream = fopen('php://memory', 'r+', false);
136
+ fputs($stream, $input);
137
+ rewind($stream);
138
+
139
+ return $stream;
140
+ }
141
+
142
+ By setting the inputStream of the `DialogHelper `, you do the same the
143
+ console would do internally with all user input through the cli. This way
144
+ you can test any user interaction (even complex ones) by passing an appropriate
145
+ input stream.
0 commit comments