Practice_PHPUnit test of STDIN
1.0.0
This is a sample PHPUnit test to check the functionability of the below function, which receives a value from "STDIN" (Standard Input) and returns that value.
function getContentsFromStdin()
{
$contents = file_get_contents('php://stdin');
if($contents === false){
throw new RuntimeException('Failed to read contents from STDIN.');
}
return $contents;
}
To test the functionability of STDIN
using PHPUnit, one way is to create a mock that overrides a php://
stream as a wrapper and replaces the value from STDIN
.
final class FunctionGetContentsFromStdinTest extends PHPUnitFrameworkTestCase
{
public function testRegularInput()
{
$result_expect = 'World!';
// Register stream wrapper "MockPhpStream" to "php://" protocol
$existed = in_array('php', stream_get_wrappers());
if ($existed) {
stream_wrapper_unregister("php");
}
stream_wrapper_register("php", '\KEINOSTestsMockPhpStream');
// Set value to STDIN
file_put_contents('php://stdin', $result_expect);
// Get value from function and restore registration
$result_actual = KEINOSSamplegetContentsFromStdin();
stream_wrapper_restore("php");
// Test
$this->assertSame($result_expect, $result_actual);
}
}
The wrapper script to mock the PHP://
stream.
This helpful wrapper was made by Denis in his blog post.
To see the tests in action clone this repo and run the test.
$ composer install
...
$ composer test
> ./vendor/bin/phpunit --testdox --bootstrap ./vendor/autoload.php tests
PHPUnit 7.5.20 by Sebastian Bergmann and contributors.
GetContentsFromFunction
Regular input
Time: 76 ms, Memory: 4.00 MB
OK (1 test, 1 assertion)
$ docker build -t test:local .
...
$ docker run --rm test:local
> ./vendor/bin/phpunit --testdox --bootstrap ./vendor/autoload.php tests
PHPUnit 9.1.3 by Sebastian Bergmann and contributors.
Get Contents From Function
Regular input
Time: 00:00.030, Memory: 4.00 MB
OK (1 test, 1 assertion)