samedi 20 décembre 2014

How to mock a repository

How can I mock database results in symfony 2, so that I can test the results of my logic? I mean, let's say I want to test the following part of some method:



if($reftab == 'ownerId')
{
$temp_id = $this->getDoctrine()
->getManager()
->getRepository('AdminBundle:Users')
->find(
$this->getDoctrine()
->getManager()
->getRepository('AdminBundle:Shop')
->getUserByRelation(
$this->getDoctrine()
->getManager()
->getRepository('AdminBundle:Shop')
->find($reftab_id)
->getShopId()
)
);
}


To do so, I'd need to mock users and shop entities, so:



$user = $this->getMock('\Acme\AdminBundle\Entity\Users');
$user->expects($this->once())
->method('getId')
->will($this->returnValue(1));
$user->expects($this->once())
->method('getEmail')
->will($this->returnValue('aaa'));

$shop = $this->getMock('\Acme\AdminBundle\Entity\Shop');
$shop->expects($this->once())
->method('getId')
->will($this->returnValue(1));
$user->expects($this->once())
->method('getEmail')
->will($this->returnValue('bbb'));

$userRepository = $this->getMockBuilder('\Doctrine\ORM\EntityRepository')
->disableOriginalConstructor()
->getMock();
$userRepository->expects($this->once())
->method('find')
->will($this->returnValue($user));

$entityManager = $this->getMockBuilder('\Doctrine\Common\Persistence\ObjectManager')
->disableOriginalConstructor()
->getMock();
$entityManager->expects($this->once())
->method('getRepository')
->will($this->returnValue($userRepository));

$temp_id = $entityManager
->getRepository('AdminBundle:Users')
->find(
$entityManager
->getRepository('AdminBundle:Shop')
->getUserByRelation(
$this->getDoctrine()
->getManager()
->getRepository('AdminBundle:Shop')
->find(1)
->getShopId()
)
);

$this->assertEqual(1, $temp_id);




The problem is however that it throws a lot of errors. find() method doesn't return the data I set in the mock object. It only returns the real existing entity record. How should I do this?


Aucun commentaire:

Enregistrer un commentaire