douzhengzuo7283 2017-04-25 15:02
浏览 88
已采纳

如何在Symfony 3中模拟'find'方法

I´m trying to mock the find method of the EntityRepository,so that the test doesn't look for the data in the database but it doesn´t seem to work. Here's the setUp method of the test class

public function setUp()
{
    parent::setUp();

    $this->client = static::createClient();
    $this->peopleManager = $this->getMockBuilder(PeopleManager::class)
        ->setMethods(['createPerson','peopleUpdate', 'peopleDelete', 'peopleRead'])
        ->disableOriginalConstructor()
        ->getMock();

   $this->repository = $this->getMockBuilder(EntityRepository::class)
       ->disableOriginalConstructor()
       ->getMock();

   $this->em = $this->getMockBuilder(EntityManager::class)
       ->disableOriginalConstructor()
       ->getMock(); 
}

This is the method where we call the find function

public function updatePersonAction($id, Request $request)
{
    $repository = $this->getDoctrine()->getRepository('GeneralBundle:People');
    $person= $repository->find($id);
    if($person)
    {
        $data = $request->request->get('array');
        $createdPeople = array();
        $UpdatedPerson = "";
        foreach($data as $content)
        {
            $prueba = $this->get('people.manager');
            $UpdatedPerson = $prueba->peopleUpdate(
                $person,
                $content['name'],
                $content['surname'],
                $content['secondSurname'],
                $content['nationality'],
                $content['birthday'],
                $content['identityCard'],
                $content['identityCardType']
            );
            array_push($createdPeople, $person);
        }
        $serializedEntity = $this->get('serializer')->serialize($UpdatedPerson, 'json');
        return new Response($serializedEntity);
    } else {
        $serializedEntity = $this->get('serializer')->serialize('Doesn\'t exists any person with this id', 'json');
        return new Response($serializedEntity);
    }
}

The debugger shows that the peoplemanager class is mocked but it doesn't mock the entity manager and the repository.

Thank you <3.

  • 写回答

1条回答 默认 最新

  • drxm5014 2017-04-25 16:38
    关注

    Suppose the class you want to test looks like this:

    // src/AppBundle/Salary/SalaryCalculator.php
    namespace AppBundle\Salary;
    
    use Doctrine\Common\Persistence\ObjectManager;
    
    class SalaryCalculator
    {
        private $entityManager;
    
        public function __construct(ObjectManager $entityManager)
        {
            $this->entityManager = $entityManager;
        }
    
        public function calculateTotalSalary($id)
        {
            $employeeRepository = $this->entityManager
                ->getRepository('AppBundle:Employee');
            $employee = $employeeRepository->find($id);
    
            return $employee->getSalary() + $employee->getBonus();
        }
    }
    

    Since the ObjectManager gets injected into the class through the constructor, it's easy to pass a mock object within a test:

    // tests/AppBundle/Salary/SalaryCalculatorTest.php
    namespace Tests\AppBundle\Salary;
    
    use AppBundle\Entity\Employee;
    use AppBundle\Salary\SalaryCalculator;
    use Doctrine\ORM\EntityRepository;
    use Doctrine\Common\Persistence\ObjectManager;
    use PHPUnit\Framework\TestCase;
    
    class SalaryCalculatorTest extends TestCase
    {
        public function testCalculateTotalSalary()
        {
            // First, mock the object to be used in the test
            $employee = $this->createMock(Employee::class);
            $employee->expects($this->once())
                ->method('getSalary')
                ->will($this->returnValue(1000));
            $employee->expects($this->once())
                ->method('getBonus')
                ->will($this->returnValue(1100));
    
            // Now, mock the repository so it returns the mock of the employee
            $employeeRepository = $this
                ->getMockBuilder(EntityRepository::class)
                ->disableOriginalConstructor()
                ->getMock();
            $employeeRepository->expects($this->once())
                ->method('find')
                ->will($this->returnValue($employee));
    
            // Last, mock the EntityManager to return the mock of the repository
            $entityManager = $this
                ->getMockBuilder(ObjectManager::class)
                ->disableOriginalConstructor()
                ->getMock();
            $entityManager->expects($this->once())
                ->method('getRepository')
                ->will($this->returnValue($employeeRepository));
    
            $salaryCalculator = new SalaryCalculator($entityManager);
            $this->assertEquals(2100, $salaryCalculator->calculateTotalSalary(1));
        }
    }
    

    In this example, you are building the mocks from the inside out, first creating the employee which gets returned by the Repository, which itself gets returned by the EntityManager. This way, no real class is involved in testing.

    Source : http://symfony.com/doc/current/testing/database.html

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器