我使用以下方法在我的PHPUnit测试中调度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());
}
但是,响应中的状态代码和标题之类的内容,(string) $response->getBody()
为空,因此我无法检查HTML中是否存在元素。当我在浏览器中运行相同的路径时,我得到了预期的HTML输出。另外,如果我echo $response->getBody(); exit;
然后在浏览器中查看输出,我会看到HTML正文。有没有理由,我的实施,我在测试中没有看到这个? (在CLI中,我猜不同的环境)
答案 0 :(得分:1)
$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));
}