我正在为我的PHP项目编写单元测试,
单元测试是模拟php://input数据,
我读了这本手册,它说:
php:// input是一个只读流,允许您从请求正文中读取原始数据.
如何php://input在PHP中模拟或编写请求主体?
这是我的源代码和单元测试,两者都是简化的.
来源:
class Koru
{
static function build()
{
// This function will build an array from the php://input.
parse_str(file_get_contents('php://input'), $input);
return $input;
}
//...
Run Code Online (Sandbox Code Playgroud)
单元测试:
function testBuildInput()
{
// Trying to simulate the `php://input` data here.
// NOTICE: THIS WON'T WORK.
file_put_contents('php://input', 'test1=foobar&test2=helloWorld');
$data = Koru::build();
$this->assertEquals($data, ['test1' => 'foobar',
'test2' => 'helloWorld']);
}
Run Code Online (Sandbox Code Playgroud)
请参阅vfsStream包以及此SO问题和答案.
基本上,您可能希望参数化读取数据以接受路径的服务:
public function __construct($path)
{
$data = file_get_contents($path); // you might want to use another FS read function here
}
Run Code Online (Sandbox Code Playgroud)
然后,在测试中,提供vfsStream流路径:
\vfsStreamWrapper::register();
\vfsStream::setup('input');
$service = new Service('vfs://input')
Run Code Online (Sandbox Code Playgroud)
在您的代码中,您将php://input按照惯例提供.
鉴于问题中的代码,最简单的解决方案是重构代码:
class Koru
{
static function build()
{
parse_str(static::getInputStream(), $input);
return $input;
}
/**
* Note: Prior to PHP 5.6, a stream opened with php://input could
* only be read once;
*
* @see http://php.net/manual/en/wrappers.php.php
*/
protected static function getInputStream()
{
return file_get_contents('php://input');
}
Run Code Online (Sandbox Code Playgroud)
并使用测试双:
class KoruTestDouble extends Koru
{
protected static $inputStream;
public static function setInputStream($input = '')
{
static::$inputStream = $input;
}
protected static function getInputStream()
{
return static::$inputStream;
}
}
Run Code Online (Sandbox Code Playgroud)
然后测试方法使用测试double,而不是类本身:
function testBuildInput()
{
KoruTestDouble::setInputStream('test1=foobar&test2=helloWorld');
$expected = ['test1' => 'foobar', 'test2' => 'helloWorld'];
$result = KoruTestDouble::build();
$this->assertSame($expected, $result, 'Stuff be different');
}
Run Code Online (Sandbox Code Playgroud)
问题中的场景的大多数困难是由静态类方法的使用引起的,静态类使测试变得困难.如果可能的话,可以避免使用静态类并使用允许使用模拟对象解决同类问题的实例方法.
| 归档时间: |
|
| 查看次数: |
4820 次 |
| 最近记录: |