Practice_PHPUnit test of STDIN
1.0.0
这是一个示例 PHPUnit 测试,用于检查以下函数的功能,该函数从“STDIN”(标准输入)接收一个值并返回该值。
function getContentsFromStdin ()
{
$ contents = file_get_contents ( ' php://stdin ' );
if ( $ contents === false ){
throw new RuntimeException ( ' Failed to read contents from STDIN. ' );
}
return $ contents ;
}
要使用 PHPUnit 测试STDIN
的功能,一种方法是创建一个模拟来覆盖php://
流作为包装器并替换STDIN
中的值。
final class FunctionGetContentsFromStdinTest extends PHPUnit Framework TestCase
{
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 = KEINOS Sample getContentsFromStdin ();
stream_wrapper_restore ( " php " );
// Test
$ this -> assertSame ( $ result_expect , $ result_actual );
}
}
用于模拟PHP://
流的包装器脚本。
这个有用的包装是由 Denis 在他的博客文章中制作的。
要查看正在运行的测试,请克隆此存储库并运行测试。
$ 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)