Skip to content

Commit debbf98

Browse files
committed
Adding description of how to test a command which expects user input
1 parent 11b63e3 commit debbf98

File tree

1 file changed

+46
-1
lines changed

1 file changed

+46
-1
lines changed

components/console/helpers/dialoghelper.rst

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,4 +97,49 @@ You can set the max number of times to ask in the ``$attempts`` argument.
9797
If you reach this max number it will use the default value, which is given
9898
in the last argument. Using ``false`` means the amount of attempts is infinite.
9999
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

Comments
 (0)