使用 PHPUnit 模拟 Slim 端点 POST 请求

Mock Slim endpoint POST requests with PHPUnit

我想用 PHPUnit 测试我的 Slim 应用程序的端点。我正在努力模拟 POST 请求,因为请求正文总是空的。

环境模拟工作正常,例如 REQUEST_URI 始终符合预期。我发现请求的正文是在 Slim\Http\RequestBody 中从 php://input 中读出的。

备注:

到目前为止我的测试代码:

//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

整个项目(请注意,我已经简化了 Whosebug 上的代码): https://github.com/famoser/SyncApi/blob/master/Famoser.SyncApi.Webpage/tests/Famoser/SyncApi/Tests/

注2: 我在 slimframework 论坛上问过,link: http://discourse.slimframework.com/t/mock-slim-endpoint-post-requests-with-phpunit/973。我会让 Whosebug 和 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());

帮助回答的原博客post在http://glenneggleton.com/page/slim-unit-testing