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\Api\Security;

use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\HttpClient\ResponseInterface;

use function Symfony\Component\String\u;

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.',
            '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

  Work with me!