Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking findOneBy"field" in doctrine2 with PHPUnit

If I mock the repository method find I get the expected results, but if I call either findBy, findOneBy, findOneById I always get null.

Code example:

$mock->expects($this->once())
                ->method('getId')
                ->will($this->returnValue(1));
$mockRepository->expects($this->any())
                         ->method('findBy') //if here I use 'find' works for all other cases always null
                         ->will($this->returnValue($mock));

Is there a reason why this happen? Is it possible to mock the "magics" method of Doctrine2 like findById or findOneById? If yes, what is wrong in my approach?

like image 451
Raffaello Avatar asked Feb 01 '26 16:02

Raffaello


1 Answers

As described in the comment, is possible with mocking the magic method call. As Example:

 // Mocked return value
 $mock->expects($this->once())
            ->method('getId')
            ->will($this->returnValue(1));

 // Example of repo mocking
 // $mockRepository= $this->getMock('Doctrine\ORM\EntityRepository', array(), array(), '', false);

$this->mockRepository
->expects($this->at(1))
->method('__call')
->with('findBy')
->will($this->returnValue($mock));

Hope this help

like image 113
Matteo Avatar answered Feb 04 '26 06:02

Matteo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!