Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony PHPUnit - Inject dependency

I want to test this TokenProvider

<?php

declare(strict_types=1);

namespace App\Services\Provider;

use App\Repository\UserRepository;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Encoder\JWTEncoderInterface;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;

/**
 * Class TokenProvider
 * @package App\Services\Provider
 */
class TokenProvider
{
    /** @var JWTEncoderInterface */
    private $JWTEncoder;
    /** @var UserPasswordEncoderInterface */
    private $passwordEncoder;
    /** @var UserRepository */
    private $userRepository;

    /**
     * TokenProvider constructor.
     *
     * @param JWTEncoderInterface          $JWTEncoder
     * @param UserPasswordEncoderInterface $passwordEncoder
     * @param UserRepository               $userRepository
     */
    public function __construct(JWTEncoderInterface $JWTEncoder, UserPasswordEncoderInterface $passwordEncoder, UserRepository $userRepository)
    {
        $this->JWTEncoder = $JWTEncoder;
        $this->passwordEncoder = $passwordEncoder;
        $this->userRepository = $userRepository;
    }

    /**
     * @param string $email
     * @param string $password
     *
     * @return string
     * @throws \Lexik\Bundle\JWTAuthenticationBundle\Exception\JWTEncodeFailureException
     */
    public function getToken(string $email, string $password): string
    {
        $user = $this->userRepository->findOneBy([
            'email' => $email,
        ]);

        if (!$user) {
            throw new NotFoundHttpException('User Not Found');
        }

        $isValid = $this->passwordEncoder->isPasswordValid($user, $password);
        if (!$isValid) {
            throw new BadCredentialsException();
        }

        return $this->JWTEncoder->encode([
            'email' => $user->getEmail(),
            'exp' => time() + 3600 // 1 hour expiration
        ]);
    }
}

Here is my test. It's not finish yet.

I want to inject JWTEncoderInterface $encoder and UserPasswordEncoder $passwordEncoder in my testGetToken().

class TokenProviderTest extends TestCase
{
    /**
     * @throws \Lexik\Bundle\JWTAuthenticationBundle\Exception\JWTEncodeFailureException
     */
    public function testGetToken()
    {
        $this->markTestSkipped();

        $JWTEncoder = //TODO;
        $passwordEncoder = //TODO;

        $tokenProvider = new TokenProvider(
            $JWTEncoder,
            $passwordEncoder,
            new class extends UserRepository{
                public function findOneBy(array $criteria, array $orderBy = null)
                {
                    return (new User())
                        ->setEmail('[email protected]')
                        ->setPassword('password')
                    ;
                }
            }
        );

        $token = $tokenProvider->getToken('[email protected]', 'password');
        $this->assertEquals(true, $token);
    }
}

What is the good way to do that in a TestCase?

I don't want to mock those two services because I want to check if my token is valid with LexikJWTAuthenticationBundle

like image 730
Kevin Avatar asked Oct 26 '18 11:10

Kevin


Video Answer


2 Answers

I came across this answer when I kept getting the following deprecation warning:

  1x: Since symfony/twig-bundle 5.2: Accessing the "twig" service directly from the container is deprecated, use dependency injection instead.
    1x in ExtensionTest::testIconsExtension from App\Tests\Templates\Icons

I got around this using:

static::bootKernel();
$container = self::$kernel->getContainer()->get('test.service_container');
$twig      = $container->get('twig');

As described in this Symfony documentation

like image 54
someonewithpc Avatar answered Sep 19 '22 12:09

someonewithpc


I recommand you to extends KernelTestCase and in function setUp() and get your dependency like this:

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

class TokenProviderTest extends KernelTestCase
{
private $jWTEncoder

protected function setUp()
{
   self::bootKernel();
   $this->jWTEncoder = self::$container->get('App\Services\TokenProvider');
}

public function testGetToken()
{
  //Your code
}
}

May this help you : https://symfony.com/doc/current/testing/doctrine.html#functional-testing

like image 25
ElliotBrl Avatar answered Sep 20 '22 12:09

ElliotBrl