10

我想测试这个 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
        ]);
    }
}

这是我的测试。它还没有完成。

我想在我JWTEncoderInterface $encoder的.UserPasswordEncoder $passwordEncodertestGetToken()

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('kevin@leroi.com')
                        ->setPassword('password')
                    ;
                }
            }
        );

        $token = $tokenProvider->getToken('kevin@leroi.com', 'password');
        $this->assertEquals(true, $token);
    }
}

在 TestCase 中这样做的好方法是什么?

我不想模拟这两个服务,因为我想检查我的令牌是否对 LexikJWTAuthenticationBundle 有效

4

3 回答 3

17

我建议您扩展 KernelTestCase 并在函数 setUp() 中获取您的依赖项,如下所示:

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
}
}

希望对您有所帮助:https ://symfony.com/doc/current/testing/doctrine.html#functional-testing

于 2018-10-26T12:43:05.770 回答
2

当我不断收到以下弃用警告时,我遇到了这个答案:

  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

我解决了这个问题:

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

本 Symfony 文档中所述

于 2021-04-01T10:21:25.290 回答
0

我在测试捆绑包时遇到了与@someonewithpc 相同的错误,扩展Kernel了测试。该test.service_container服务不可用。

我必须设置framework.test为:trueFrameworkBundle

/**
 * This is not the full class, unrelated code have been removed for clarity
 */
class MyBundleTestKernel extends Kernel
{
    public function registerBundles()
    {
        return [
            new FrameworkBundle(),
            new MyBundle(),
        ];
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(function (ContainerBuilder $container) {
            $container->prependExtensionConfig('framework', ['test' => true]);
        });
    }
}
于 2021-11-14T13:01:11.827 回答