gpt4 book ai didi

php - 使用 PHPUnit 测试 Slim 3 路由时 $response->getBody() 为空

转载 作者:可可西里 更新时间:2023-10-31 23:38:15 28 4
gpt4 key购买 nike

我使用以下方法在我的 PHPUnit 测试中分派(dispatch) Slim 应用程序的路由:

protected function dispatch($path, $method='GET', $data=array())
{
// Prepare a mock environment
$env = Environment::mock(array(
'REQUEST_URI' => $path,
'REQUEST_METHOD' => $method,
));

// Prepare request and response objects
$uri = Uri::createFromEnvironment($env);
$headers = Headers::createFromEnvironment($env);
$cookies = [];
$serverParams = $env->all();
$body = new RequestBody();

// create request, and set params
$req = new Request($method, $uri, $headers, $cookies, $serverParams, $body);
if (!empty($data))
$req = $req->withParsedBody($data);

$res = new Response();

$this->headers = $headers;
$this->request = $req;
$this->response = call_user_func_array($this->app, array($req, $res));
}

例如:

public function testGetProducts()
{
$this->dispatch('/products');

$this->assertEquals(200, $this->response->getStatusCode());
}

但是,尽管响应中包含状态代码和 header 之类的内容,但 (string) $response->getBody() 是空的,因此我无法检查元素是否存在HTML。当我在浏览器中运行相同的路由时,我得到了预期的 HTML 输出。另外,如果我 echo $response->getBody(); exit; 然后在浏览器中查看输出,我看到了 HTML 正文。有什么原因,在我的实现中,我没有在我的测试中看到这个? (在 CLI 中,我猜环境如此不同)

最佳答案

$response->getBody() 将是空的,因为您已经设置了已解析的正文。将它作为字符串放入 RequestBody 中会更容易,其方式与它通过网络传入时的设置方式相同。

也就是像这样:

protected function dispatch($path, $method='GET', $data=array())
{
// Prepare a mock environment
$env = Environment::mock(array(
'REQUEST_URI' => $path,
'REQUEST_METHOD' => $method,
'CONTENT_TYPE' => 'application/json',
));

// Prepare request and response objects
$uri = Uri::createFromEnvironment($env);
$headers = Headers::createFromEnvironment($env);
$cookies = [];
$serverParams = $env->all();
$body = new RequestBody();
if (!empty($data)) {
$body->write(json_encode($data));
}

// create request, and set params
$req = new Request($method, $uri, $headers, $cookies, $serverParams, $body);
$res = new Response();

$this->headers = $headers;
$this->request = $req;
$this->response = call_user_func_array($this->app, array($req, $res));
}

关于php - 使用 PHPUnit 测试 Slim 3 路由时 $response->getBody() 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34823328/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com