如何在ZF2中测试自定义学说保水器?

时间:2015-08-24 12:15:34

标签: php doctrine-orm zend-framework2 doctrine phpunit

为了向DoctrineModule\Stdlib\Hydrator\DoctrineObject添加一些额外的(过滤)功能,我将其扩展并创建了类EntityHydrator

namespace MyLib\Model\Entity\Hydrator;

class EntityHydrator extends \DoctrineModule\Stdlib\Hydrator\DoctrineObject
{
    protected $foo;
    protected $bar;

    public function __construct(
        \Doctrine\Common\Persistence\ObjectManager $objectManager,
        $byValue = true,
        $foo = true
    ) {
        parent::__construct($objectManager, $byValue);
        $this->setFoo($foo);
    }

    public function extract($object)
    {
        $extractedArray = parent::extract($object);
        $extractedArray = $this->getFoo()
            ? $this->performAdditionalFunctionality($extractedArray)
            : $extractedArray
        ;
        return $extractedArray;
    }

    // access methods for $foo and $bar

    // private/protected methods like performAdditionalFunctionality(...) and other
}

现在课程应该进行单元测试。问题是extract(...)的测试。此方法基于\DoctrineModule\Stdlib\Hydrator\DoctrineObject#extract(...)。这意味着我需要一个EntityHydrator / DoctrineObject - 包含所有依赖项。处理这个并获得定制(学说)水合器单元测试的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

在这种情况下你应该使用composition over inheritance

namespace MyLib\Model\Entity\Hydrator;

use Zend\Stdlib\Hydrator\HydratorInterface;

class EntityHydrator implements HydratorInterface
{
    protected $foo;
    protected $bar;
    protected $doctrineObjectHydrator;

    public function __construct(HydratorInterface $doctrineObjectHydrator, $foo = true)
    {
        $this->doctrineObjectHydrator = $doctrineObjectHydrator;
        $this->setFoo($foo);
    }

    public function extract($object)
    {
        $extractedArray = $this->doctrineObjectHydrator->extract($object);
        $extractedArray = $this->getFoo()
            ? $this->performAdditionalFunctionality($extractedArray)
            : $extractedArray
        ;
        return $extractedArray;
    }

    // access methods for $foo and $bar

    // private/protected methods like performAdditionalFunctionality(...) and other
}

现在,您可以轻松模拟原始的DoctrineObject水化器,并仅在新的水化器中测试逻辑。