$ response-> getBody () is empty when testing Slim 3 routes using PHPUnit

I use the following method to send the Slim route in my PHPUnit tests:

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));
}

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)

+4
source share
1 answer

$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));
}
+1

Source: https://habr.com/ru/post/1624541/


All Articles