Migrating from Slim 3 to 4: Writing PHP Unit Tests

Hi community,

I was using Slim 3 and am now migrating to Slim 4.

I was able to execute PHP Unit Tests in Slim 3 and try to rewrite them to Slim 4. Here is a simplified code snippet:

use \PHPUnit\Framework\TestCase;
use \RestApp;
use \Slim\Psr7\Environment;
use \Slim\Psr7\Request;

class RestAppTest extends TestCase {
    private $app;

    public function setUp() {
        $this->app = new RestApp();

    public function testFunctionality() {
        $env = Environment::mock([
            'REQUEST_METHOD' => 'POST',
            'REQUEST_URI'    => '/v1/Users'
        $req = Request::createFromEnvironment($env);
        $attributes = array();
        $req = $req->withParsedBody($attributes);
        $this->app->getApp()->getContainer()['request'] = $req;
        $response = $this->app->run(true);
        $this->assertSame($response->getStatusCode(), 201);


Unfortunately, Request::createFromEnvironment($env); is not available any more on \Slim\Psr7\Request. How am I able to create a \Slim\Psr7\Request from the environment?

Thanks in advance!

When I migrated from Slim 3 to Slim 4, I had the same or similar issue with tests.

I solved it creating a new class and file TestCase.php with the createRequest function:

    protected function createRequest(
        string $method,
        string $path,
        array $headers = ['HTTP_ACCEPT' => 'application/json'],
        array $cookies = [],
        array $serverParams = []
    ): Request {
        $uri = new Uri('', '', 80, $path);
        $handle = fopen('php://temp', 'w+');
        $stream = (new StreamFactory())->createStreamFromResource($handle);

        $h = new Headers();
        foreach ($headers as $name => $value) {
            $h->addHeader($name, $value);

        return new SlimRequest($method, $uri, $h, $cookies, $serverParams, $stream);

And then, you can use this createRequest function in your tests:

    public function testFunctionalityWithPost()
        $attributes = [];
        $req = $this->createRequest('POST', '/v1/Users');
        $request = $req->withParsedBody($attributes);
        $response = $app->handle($request);

        $this->assertEquals(201, $response->getStatusCode());

Check the createRequest function from Slim Skeleton:

My tests examples with Slim 4:

1 Like

There is an example of how to do this on Slim-Skeleton https://github.com/slimphp/Slim-Skeleton/blob/master/tests/TestCase.php#L68-L86

1 Like

Thanks a lot @maurobonfietti. I was able to rewrite my test cases and successfully migrated to Slim 4.


1 Like