Testing a JSON login with the API-Platform ApiTestCase class

Published on 2021-10-31 • Modified on 2021-10-31

In this snippet, we see how to test a JSON login with the API-Platform ApiTestCase class. We pass the username and password with the json option; then, e can convert the response to an array to get the security token.



namespace App\Tests\Security;

use ApiPlatform\Core\Bridge\Symfony\Bundle\Test\ApiTestCase;
use Symfony\Component\HttpFoundation\Response;
use function Symfony\Component\String\u;
use Symfony\Contracts\HttpClient\ResponseInterface;

final class JsonLoginTest extends ApiTestCase
    public function testLoginOK(): void
        $response = $this->login('reader', 'test');
        $arrayResponse = $response->toArray();
        self::assertArrayHasKey('token', $arrayResponse);

    public function testLoginNOK(): void
        $this->login('reader', 'wrong password');
        self::assertResponseHeaderSame('content-type', 'application/json');
            'code' => Response::HTTP_UNAUTHORIZED,
            'message' => 'Invalid credentials.',

     * JSON Login try with a given email and password.
    public function login(string $username, string $password): ResponseInterface
        return self::createClient()->request('POST', '/api/login_check', [
            'json' => compact('username', 'password'),

 More on Stackoverflow   Read the doc  More on the web  Random snippet