模拟纤细终端使用PHPUnit的POST请求

2022-06-13 00:00:00 php slim

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

  • 我尝试了如下所述的方法:Slim Framework endpoint unit testing。(添加环境变量slim-input)
  • 我已尝试直接写入php://input,但我发现php://input是只读的(通过困难的方式)
环境的模拟工作正常,例如REQUEST_URI总是如预期的那样。我发现请求的正文在SlimHttpRequestBodyphp://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: 我在瘦身框架论坛上问过,link: http://discourse.slimframework.com/t/mock-slim-endpoint-post-requests-with-phpunit/973。我将使Stackoverflow和Disourse.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

相关文章