PHPUnit:PHP致命错误:在非对象上调用成员函数find()

时间:2014-07-08 06:58:15

标签: php unit-testing phpunit

我的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]);

但是在测试后我收到错误: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的__construct表单中,我调用了父:: __结构:

public function __construct($entityManager, $entityClass, $guzzleClient, $serializer, $apiSettings)
    {
        parent::__construct($entityManager, $entityClass, $guzzleClient, $serializer, $apiSettings);
    }

在我的父:: __构造中,它看起来像这样:

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;
    }

没有测试的代码工作正常,但我不知道在测试时会出现什么问题。任何的想法? 致谢!!!

1 个答案:

答案 0 :(得分:2)

拥有它,这太简单了,而且我真的很愚蠢:

错误:

$reviewHandler = $this->getMock(
            'My\Bundle\Handler\RevHandler',
            array('saveEntity'),
            array(
                $this->entityManager,
                'My\Bundle\Entity\Rev',
                $this->guzzleClient,
                $this->serializer,
                $this->apiSettings
            )
        );

RIGHT:

$reviewHandler = $this->getMock(
            'My\Bundle\Handler\RevHandler',
            array('findEntityById'),
            array(
                $this->entityManager,
                'My\Bundle\Entity\Rev',
                $this->guzzleClient,
                $this->serializer,
                $this->apiSettings
            )
        );

我给了我的模拟对象错误的功能!错误:saveEntity右:findEntityById