错误:单元测试时无法实例化接口符号

时间:2018-08-24 21:09:33

标签: php symfony

我正在尝试对一种注册方法进行单元测试,并在此guide之后进行即时测试。我是单元测试的新手。

我不断得到

  

1)App \ Tests \ Controller \ SignUpControllerTest :: testSignUp错误:无法   实例化接口   Symfony \ Component \ Security \ Core \ Encoder \ UserPasswordEncoderInterface

     

/Applications/MAMP/htdocs/my_project/tests/Controller/SignUpControllerTest.php:19

我只是认为我没有正确执行此单元测试。这就是我所拥有的。我不确定自己在做什么。我要做的就是测试注册方法。

UserController.php

public function signup(Request $request, UserPasswordEncoderInterface $passwordEncoder )
{
    $user = new User();

    $entityManager = $this->getDoctrine()->getManager();

    $user->setEmail($request->get('email'));
    $user->setPlainPassword($request->get('password'));
    $user->setUsername($request->get('username'));
    $password = $passwordEncoder->encodePassword($user, $user->getPlainPassword());
    $user->setPassword($password);

    $entityManager->persist($user);
    $entityManager->flush();

    return $this->redirectToRoute('login');



}

SignUpControllerTest.php

namespace App\Tests\Controller;

use App\Entity\Product;
use App\Controller\UserController;
use App\Entity\User;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\Persistence\ObjectRepository;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

class SignUpControllerTest extends WebTestCase
{

    public function testSignUp()
    {   
        $passwordEncoder = new UserPasswordEncoderInterface();
        $user = new User();
        $user->setEmail('janedoe123@aol.com');
        $user->setPlainPassword('owlhunter');
        $user->setUsername('BarnMan');
        $password = $passwordEncoder->encodePassword($user, $user->getPlainPassword());
        $user->setPassword($password);

        $userRepository = $this->createMock(ObjectRepository::class);
        $userRepository->expects($this->any())
            ->method('find')
            ->willReturn($user);


        $objectManager = $this->createMock(ObjectManager::class);
        // use getMock() on PHPUnit 5.3 or below
        // $objectManager = $this->getMock(ObjectManager::class);
        $objectManager->expects($this->any())
            ->method('getRepository')
            ->willReturn($userRepository);

        $userController = new UserController($objectManager);
        $this->assertEquals(2100, $userController->signupTest());

    }


}

1 个答案:

答案 0 :(得分:1)

错误非常清楚。在testSignUp方法的第一行中,您是在接口外创建实例,而该实例无法在PHP中完成。

要在单元测试中从接口创建可用的对象,请为其创建一个模拟对象。为此,请阅读PHP单元文档。