I want to test the endpoints of my Slim application with PHPUnit. I’m struggling to mock POST requests (the request body is always empty).
- I’ve tried the approach as described here: LINK_OMITTED. (adding the environment variable slim-input)
- I’ve tried writing to php://input directly, but I’ve found out php://input is read only (the hard way)
The emulation of the environment works correctly as for example the REQUEST_URI is always as expected. I’ve found out that the body of the request is read out in Slim\Http\RequestBody from php://input.
my test code so far:
//inherits from Slim/App $this->app = new SyncApiApp(); // write json to //temp, does not work $tmp_handle = fopen('php://temp', 'w+'); fwrite($tmp_handle, $json); rewind($tmp_handle); fclose($tmp_handle); //override environment $this->app->container["environment"] = Environment::mock( [ 'REQUEST_METHOD' => 'POST', 'REQUEST_URI' => '/1.0/' . $relativeLink, 'slim.input' => $json, 'SERVER_NAME' => 'localhost', 'CONTENT_TYPE' => 'application/json;charset=utf8' ] ); //run the application $response = $this->app->run(); //result: the correct endpoint is reached, but $request->getBody() is empty
My test code on github (be aware that I’ve simplified the code in the example): LINK_OMITTED
- I want to avoid calling the controller methods directly, so I can test everything, including endpoints.
- I want to avoid guzzle because it sends an actual request. I do not want to have a server running while testing the application.
- I’ve posted the exact same question to stackoverflow 2 days ago: http://stackoverflow.com/questions/40867377/mock-slim-endpoint-post-requests-with-phpunit. I hope you’re not mad about this, and I promise to keep both sites up to date You’ll find there all the omitted links too
- I’d be very open for suggestions on how to improve the architecture of the application if something caches your attention