我想使用PHPUnit测试我的Slim应用程序的端点。 我无法模拟POST请求,因为请求体始终为空。
- 我尝试了这里描述的方法:Slim Framework endpoint unit testing。(添加环境变量
slim-input
) - 我尝试直接写入
php://input
,但是我发现php://input
是只读的(通过艰辛的方式)
环境的仿真工作正常,例如REQUEST_URI
始终如预期。 我发现请求的正文在Slim\Http\RequestBody
中从php://input
读取。
注:
- 我希望避免直接调用控制器方法,以便我可以测试所有内容,包括端点。
- 我希望避免使用
guzzle
,因为它会发送实际请求。 我不想在测试应用程序时运行服务器。
到目前为止,我的测试代码:
//inherits from Slim/App
$this->app = new SyncApiApp();
// write json to //temp, does not work
$tmp_handle = fopen('php://temp', 'w+');
fwrite($tmp_handle, $json);
rewind($tmp_handle);
fclose($tmp_handle);
//override environment
$this->app->container["environment"] =
Environment::mock(
[
'REQUEST_METHOD' => 'POST',
'REQUEST_URI' => '/1.0/' . $relativeLink,
'slim.input' => $json,
'SERVER_NAME' => 'localhost',
'CONTENT_TYPE' => 'application/json;charset=utf8'
]
);
//run the application
$response = $this->app->run();
//result: the correct endpoint is reached, but $request->getBody() is empty
整个项目(请注意,我在stackoverflow上简化了代码):https://github.com/famoser/SyncApi/blob/master/Famoser.SyncApi.Webpage/tests/Famoser/SyncApi/Tests/ 注2: 我在slimframework论坛上提出了问题,链接如下: http://discourse.slimframework.com/t/mock-slim-endpoint-post-requests-with-phpunit/973。我会让stackoverflow和discourse.slimframework保持同步。
注3: 目前我有一个关于此功能的pull request: https://github.com/slimphp/Slim/pull/2086
$request->getBody()
为空。 - Florian Moser