Search code examples
dependency-injectionfunctional-testingsymfony4

Load service in functional test (Symfony4)


I'm trying to test a controller made with Symfony 4 with PHPUnit. I'm using https://github.com/lexik/LexikJWTAuthenticationBundle to manage JWT.

This controllers should return a 200 if a valid JWT is given, a 401/403 otherwise.

The first part with the 401 response is easy: I just don't send any token

<?php

namespace App\Tests\Controller;

Class GraphQLControllerTest extends \Symfony\Bundle\FrameworkBundle\Test\WebTestCase {

    function test_token(){

        $client = static::createClient();
        $client->request('GET', '/graphql');

        // Check 401 response
        $response = $client->getResponse();
        $this->assertSame(401, $response->getStatusCode());
        $this->assertSame('"Not authenticated"', $response->getContent());

    }
}

The next part is tricky: how do I get my JWT encoder service in my test_token method in order to generate some tokens to test 200 and 403 responses?

If I were in a controller I could use Symfony autowiring or make a public alias of lexik_jwt_authentication.encoder to be used like this:

$this->container->get('lexik_jwt_authentication.encoder')

Loading manually the service in my test like this bellow seems inefficient as some of the arguments of the constructor are some objects, and some arguments of their own constructor are objects, and ...

new Lexik\Bundle\JWTAuthenticationBundle\Encoder\DefaultEncoder([some objects here])

This is what is nice with autowiring: you just get the service you want ready to be used.

=> What's the best way to get this service in my test?

Thanks!


Solution

  • It's now possible with Symfony 4.1 to load a private service within a test using the KernelTestCase