PHPUnit:PHP致命错误:对非对象调用成员函数find()
我的HandlerClass中有一个功能运行良好:PHPUnit:PHP致命错误:对非对象调用成员函数find(),php,unit-testing,phpunit,Php,Unit Testing,Phpunit,我的HandlerClass中有一个功能运行良好: /** * @param $entity * @return null|object */ public function findEntityById($id) { if($id) { $entity = $this->repository->find($id); if (empty($entity)) {
/**
* @param $entity
* @return null|object
*/
public function findEntityById($id)
{
if($id)
{
$entity = $this->repository->find($id);
if (empty($entity)) {
return false;
}
return $entity;
}
return false;
}
我为一个函数编写了一个测试:getCheckedList(),它使用这个函数:findEntityById()。我模拟了函数findEntityById(),因此它应该返回false
$reviewHandler = $this->getMock(
'My\Bundle\Handler\RevHandler',
array('saveEntity'),
array(
$this->entityManager,
'My\Bundle\Entity\Rev',
$this->guzzleClient,
$this->serializer,
$this->apiSettings
)
);
$reviewHandler->expects($this->once())
->method('findEntityById')
->will($this->returnValue(false));
$result = $reviewHandler->getCheckedList(22);
$this->assertArrayHasKey(0,$result);
$this->assertEquals(22,$result[0]);
但是在我的测试之后,我得到了一个错误:report:phpunit
PHP Fatal error: Call to a member function find() on a non-object on line 152
这是我函数中的这一行:findEntityById(),它被模拟,并在我的测试中抛出一个错误:
$entity = $this->repository->find($id);
在我的RevHandler的_构造表单中,我调用父::_构造:
public function __construct($entityManager, $entityClass, $guzzleClient, $serializer, $apiSettings)
{
parent::__construct($entityManager, $entityClass, $guzzleClient, $serializer, $apiSettings);
}
在my parent::_构造中,它看起来像这样:
public function __construct(EntityManager $entityManager, $entityClass, $guzzleClient, $serializer, $apiSettings)
{
$this->entityManager = $entityManager;
$this->entityClass = $entityClass;
$this->repository = $this->entityManager->getRepository($this->entityClass);
$this->guzzleClient = $guzzleClient;
$this->serializer = $serializer;
$this->apiSettings = $apiSettings;
}
没有测试的代码运行良好,但我不知道在测试时会出现什么错误。有什么想法吗?
谢谢 有了它,这太简单了,我真是愚蠢的失败: 错:
$reviewHandler = $this->getMock(
'My\Bundle\Handler\RevHandler',
array('saveEntity'),
array(
$this->entityManager,
'My\Bundle\Entity\Rev',
$this->guzzleClient,
$this->serializer,
$this->apiSettings
)
);
对:
$reviewHandler = $this->getMock(
'My\Bundle\Handler\RevHandler',
array('findEntityById'),
array(
$this->entityManager,
'My\Bundle\Entity\Rev',
$this->guzzleClient,
$this->serializer,
$this->apiSettings
)
);
我给了我的模拟对象错误的函数!错误:saveEntity正确:FindentialById您是否在任何地方分配了
$this->repository
?这应该是一个问题,我该怎么做?我用家长更新了我的问题::_构造,请看一看。你为什么认为它是一个对象?您的$this->entityManager->getRepository
没有返回您所认为的内容。如何将存储库设置为对象?它应该在我的父项中自动设置::u构造?!