故障单元/功能测试的symfony 4.2

问题描述 投票:2回答:2

我写代码symfony的4.2执行单元测试,实际上现在用智威汤逊验证包生成令牌。我想测试记号是否成功与否产生。请有给它的外观和建议我,如果有任何需要改进。

在登录控制器代码

<?php

namespace App\Controller;

use App\Entity\Organization;
use Doctrine\Common\Annotations\AnnotationReader;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

class LoginController extends AbstractController
{
protected $serializer;

protected $logger;

public function __construct(LoggerInterface $logger)
{
    $this->logger = $logger;
    $encoders = array(new XmlEncoder(), new JsonEncoder());
    $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
    $normalizer = new ObjectNormalizer($classMetadataFactory);
    $normalizer->setCircularReferenceLimit(2);
    $normalizer->setCircularReferenceHandler(function ($object) {
        return $object->getId();
    });
    $normalizers = array($normalizer);
    $this->serializer = new Serializer($normalizers, $encoders);
}

/**
 * Check the credentials are valid
 * Check whether the user is verified
 * Generate JWT token for authentic users and return
 *
 * @Route("/api/login_check", name="login_check")
 */
public function login(Request $request, JWTTokenManagerInterface $JWTTokenManager, UserProviderInterface $userProvider, UserPasswordEncoderInterface $encoder)
{
    try {
        $data = json_decode($request->getContent());
        $user = $userProvider->loadUserByUsername($data->email);
        $passwordValid = $encoder->isPasswordValid($user, $data->password);
        if ($passwordValid) {
            if ($user->getVerified()) {
                $organization = $user->getOrganization();
                $organization = $this->getDoctrine()->getRepository(Organization::class)->findOneBy(array('id' => $organization->getId()));
                $token = $JWTTokenManager->create($user);
                return new JsonResponse(['token' => $token, 'user' => $this->serializer->normalize($user, 'json')]);
            } else {
                $array = array('message' => 'User not verified');
                $response = new Response(json_encode($array), 401);
                $response->headers->set('Content-Type', 'application/json');
                return $response;
            }
        } else {
            $array = array('message' => 'Bad credentials');
            $response = new Response(json_encode($array), 401);
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        }
    } catch (\Exception $e) {
        return new Response($e->getMessage());
    }
}
}

在测试/控制器文件夹代码

    namespace App\Tests\Controller

use App\Controller\Log;
use App\Controller\LoginController;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\LoggerInterface;

class LoginTest extends TestCase{

    protected $logger;
    protected $controller;
/**
 *
 */
public function setUp()
{
    $this->logger = $this->createMock(LoggerInterface::class);

    $this->controller = new LoginController(
        $this->logger
    );

    parent::setUp();
}

public function testlogin()
{
    $result = $this->controller->login('Test');
    $this->assertEquals( 'TEST1548303737',$result);
}

}

php unit-testing symfony
2个回答
0
投票

你的“登陆”行动需要2个参数,你需要模拟请求和JWTManagerInterface来。

另一个想法:通过Symfony的功能测试替换单元测试。实施例(改编自symfony的DOC):

namespace App\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class LoginControllerTest extends WebTestCase
{
    public function testCheckLogin()
    {
        $client = static::createClient();
        $client->request('POST', '/api/login_check', [], [], [], 'test');

        $this->assertEquals(200, $client->getResponse()->getStatusCode());
        $this->assertEquals('TEST1548303737', $client->getResponse()->getContent());
    }
}

0
投票

你只需要模拟请求和智威汤逊的管理界面

© www.soinside.com 2019 - 2024. All rights reserved.