我有一个函数在我的HandlerClass工作良好:
/**
* @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]);
但是我得到一个错误后,我的测试:报告:phpunit
PHP Fatal error: Call to a member function find() on a non-object on line 152
这是我的函数中的这一行:findEntityById()它被模拟并在我的测试中抛出错误:
$entity = $this->repository->find($id);
在我的RevHandler的__construct中,我调用了父类::__construct:
public function __construct($entityManager, $entityClass, $guzzleClient, $serializer, $apiSettings)
{
parent::__construct($entityManager, $entityClass, $guzzleClient, $serializer, $apiSettings);
}
在我的parent::__construct中,它看起来像这样:
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
)
);
我给了错误的函数给我的模拟对象!正确:findEntityById