Migrating from Slim 3 to 4: Writing PHP Unit Tests

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