用PHPUnit嘲笑教义2中的findOneBy“field”


Mocking findOneBy"field" in doctrine2 with PHPUnit

如果我模拟存储库方法find我得到预期的结果,但是如果我打电话给findByfindOneByfindOneById我总是得到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));

发生这种情况有什么原因吗?是否可以像findByIdfindOneById一样嘲笑教义2的"魔法"方法?如果是,我的方法有什么问题?

如注释中所述,可以通过模拟魔术方法调用来实现。例如:

 // 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));

希望这个帮助