【发布时间】:2016-03-04 20:32:23
【问题描述】:
我使用以下方法在我的 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 中,我猜是不同的环境)
【问题讨论】: