我想用 PHPUnit 测试我的 Slim 应用程序的端点。我正在努力模拟 POST 请求,因为请求正文始终为空。
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:
我的这个功能目前有一个开放的拉取请求:https://github.com/slimphp/Slim/pull/2086
最佳答案
在 http://discourse.slimframework.com/t/mock-slim-endpoint-post-requests-with-phpunit/973/7 有帮助,解决方案是创建 Request
从头开始,并写入请求正文。
//setup environment vals to create request
$env = Environment::mock();
$uri = Uri::createFromString('/1.0/' . $relativeLink);
$headers = Headers::createFromEnvironment($env);
$cookies = [];
$serverParams = $env->all();
$body = new RequestBody();
$uploadedFiles = UploadedFile::createFromEnvironment($env);
$request = new Request('POST', $uri, $headers, $cookies, $serverParams, $body, $uploadedFiles);
//write request data
$request->write(json_encode([ 'key' => 'val' ]));
$request->getBody()->rewind();
//set method & content type
$request = $request->withHeader('Content-Type', 'application/json');
$request = $request->withMethod('POST');
//execute request
$app = new App();
$resOut = $app($request, new Response());
$resOut->getBody()->rewind();
$this->assertEquals('full response text', $resOut->getBody()->getContents());
有助于回答的原始博客文章位于 http://glenneggleton.com/page/slim-unit-testing
关于php - 使用 PHPUnit 模拟 Slim 端点 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40867377/