使用PHPUnit在doctrine2中模拟findOneBy"field"

Raf*_*llo 3 php phpunit unit-testing mocking doctrine-orm

如果我嘲笑库方法find我得到预期的结果,但如果我叫要么findBy,findOneBy,findOneById我总是得到null.

代码示例:

$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));
Run Code Online (Sandbox Code Playgroud)

有这种情况发生的原因吗?是否有可能嘲笑Doctrine2的"魔法"方法findById或者findOneById?如果是的话,我的方法出了什么问题?

Mat*_*teo 6

如评论中所述,可以通过模拟魔术方法调用来实现.例如:

 // 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));
Run Code Online (Sandbox Code Playgroud)

希望这有帮助