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 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题