【问题标题】:How to test a custom doctrine hydrator in ZF2?如何在 ZF2 中测试自定义的学说水合器?
【发布时间】:2015-11-17 20:44:47
【问题描述】:

为了向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——及其所有依赖项。处理此问题并获得自定义(教义)水合器单元测试的最佳方法是什么?

【问题讨论】:

  • 为什么要测试 DoctrineObject,你的目标应该是单独测试你的功能对吧?
  • 对,但是例如我的EntityHydrator#extract(...) 是我的功能(它使用parent::extract(...) 并在它执行一些特定的sutff 之后)并且应该对其进行测试。再一次:问题是,我的EntityHydratoris a/扩展DoctrineObject。这意味着:如果我想测试它,我必须创建一个和EntityHydrator——并且创建一个EntityHydrator 需要DoctrineObject 的所有依赖项并且需要付出很多努力。

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


【解决方案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 hydrator 并在新的 hydrator 中仅测试逻辑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-20
    • 1970-01-01
    • 2013-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多