mardi 28 juin 2016

PHPUnit mocking object that is the same type as the SUT and is a property of the SUT

I have a class called TestClass which has a property called parent. The parent property is the same type as the TestClass. Show below is a portion of the TestClass I am trying to test.

class TestClass
{
    /**
     * @param array $parentIds
     * @return ApiLock[]
     */
    protected function getParentLocks(array $parentIds)
    {
        if ($this->getParent()) {
            $id = array_pop($parentIds);
            return $this->getParent()->getLocks($id, $parentIds);
        }

        return [];
    }

    /**
     * @param array $ids
     * @return ApiLock[]
     */
    protected function getLocks($id, array $ids)
    {
        $locks = $this->getParentLocks($ids);

        if ($this->config->getLockName()) {
            $locks[] = new ApiLock($this->config->getLockName() . '.' . $id, $this->config->getLockWait());
        }

        return $locks;
    }

}

The method getLocks calls the getParentLocks method. To test this class, I have mocked TestClass object and set as the parent of the SUT. Something similar to this.

$apiLock = $this->getMockBuilder(ApiLock::class)
            ->disableOriginalConstructor()
            ->getMock();
        $parent = $this->getMockBuilder(TestClass::class)
            ->disableOriginalConstructor()
            ->getMock();

        $parent->expects($this->any())
            ->method('getLocks')
            ->will($this->returnValue([$apiLock]));

        $testClass->setParent($parent);

But when i run the tests , the method setLocks on the parent object will not return the stubbed value but will actually call the setLocks method on the parent object and the test fails. May be I am not seeing something obvious. The stubbed method should be called instead of the real method on the parent object. Please help me thanks in advance.

Aucun commentaire:

Enregistrer un commentaire