lundi 4 juillet 2016

Symfony Mock repository in PHU Unit test

I have a test which connect to the database. So I decided to mock my repository. First time I'm doing that, so I'm little bit confuse.

I'm following this documentation: http://ift.tt/29pse5l

My test code:

// First, mock the object to be used in the test
        $averagePrice = $this->getMock('\FMPriceBundle\Service\PriceService');
        $averagePrice->expects($this->once())
            ->method('getFuelPrice')
            ->will($this->returnValue(1000));

        // Now, mock the repository so it returns the mock of the employee
        $averagePriceRepository = $this->getMockBuilder('FM\PriceBundle\Repository\AveragePriceRepository')
            ->disableOriginalConstructor()
            ->getMock();
        $averagePriceRepository->expects($this->once())
            ->method('find')
            ->will($this->returnValue($averagePrice));

        // Last, mock the EntityManager to return the mock of the repository
        $entityManager = $this
            ->getMockBuilder('\Doctrine\Common\Persistence\ObjectManager')
            ->disableOriginalConstructor()
            ->getMock();
        $entityManager->expects($this->once())
            ->method('getRepository')
            ->will($this->returnValue($averagePriceRepository));

My service:

public function getFuelPrice($productId, $id, $location, $date = null)
    {
        $em = $this->entityManager;

        /** @var AveragePrice $price */
        $amount =  $em->getRepository('FMPriceBundle:AveragePrice')
            ->getPrice($productId, $id, $location, $date)
            ->getQuery()
            ->getOneOrNullResult();

        if($amount === null){
            throw new Exception('Pas de prix trouvé');
        }

        return $amount["amount"];
    }

I have this error:

1) FM\PriceBundle\Tests\Service\PriceServiceTest::testFuelPrice Trying to configure method "getFuelPrice" which cannot be configured because it does not exist, has not been specified, is final, or is static

Aucun commentaire:

Enregistrer un commentaire