I use the following method to send the Slim route in my PHPUnit tests:
protected function dispatch($path, $method='GET', $data=array())
{
$env = Environment::mock(array(
'REQUEST_URI' => $path,
'REQUEST_METHOD' => $method,
));
$uri = Uri::createFromEnvironment($env);
$headers = Headers::createFromEnvironment($env);
$cookies = [];
$serverParams = $env->all();
$body = new RequestBody();
$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));
}
For example:
public function testGetProducts()
{
$this->dispatch('/products');
$this->assertEquals(200, $this->response->getStatusCode());
}
However, in the answer, things like the status code and the header are (string) $response->getBody()empty, so I cannot check for elements in the HTML. When I run the same route in the browser, I get the expected HTML output. Also, if I echo $response->getBody(); exit;then look at the output in a browser, I see the body of the HTML. Is there any reason, with my implementation, I do not see this in my tests? (in the CLI, I think such a different environment)
source
share