用PHPUnit模拟Slim端点POST请求
问题描述:
我想用PHPUnit测试我的Slim应用程序的端点。我努力模拟POST请求,因为请求主体总是空的。用PHPUnit模拟Slim端点POST请求
- 我试过这里描述的方法:Slim Framework endpoint unit testing。 (添加环境变量
slim-input
) - 我试着写
php://input
直接,但我发现了php://input
是只读的(艰难地)
环境的仿真工作正常,例如REQUEST_URI
始终如预期。我发现请求的正文是从php://input
的Slim\Http\RequestBody
中读出的。
注:
- 我想避免直接调用控制器方法,这样我就可以检验一切,包括端点。
- 我想避免
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
整个项目(要知道,我已经简化计算器上的代码): 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
为什么不直接使用z.b.发送POST请求然后Gu?? – Tebe
我改变了我的问题的标题。我想用PHPUnit来测试端点 –
您能否给我们一个示例端点和测试?我不确定你提供的代码试图做什么。 – nerdlyist