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


i use following method dispatch slim app's route in phpunit tests:

protected function dispatch($path, $method='get', $data=array()) {     // prepare mock environment     $env = environment::mock(array(         'request_uri' => $path,         'request_method' => $method,     ));      // prepare request , response objects     $uri = uri::createfromenvironment($env);     $headers = headers::createfromenvironment($env);     $cookies = [];     $serverparams = $env->all();     $body = new requestbody();      // create request, , 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, as things status code , header in response, (string) $response->getbody() empty cannot check presence of elements in html. when run same route in browser, expected html output. also, if echo $response->getbody(); exit; , view output in browser, see html body. there reason, implementation, i'm not seeing in tests? (in cli, different environment guess)

$response->getbody() empty you've set parsed body. it's easier put requestbody string in same way set if came in on wire.

i.e this:

protected function dispatch($path, $method='get', $data=array()) {     // prepare mock environment     $env = environment::mock(array(         'request_uri' => $path,         'request_method' => $method,         'content_type' => 'application/json',     ));      // prepare request , 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, , 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)); } 

Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -