如何在单元测试中覆盖工厂闭包

时间:2014-08-16 14:36:11

标签: zend-framework2

在我的Module.php中,我有这个Controller Config:

public function getControllerConfig() {
    return array(
        'factories' => array(
            'Application\Controller\Persons' => function($serviceLocator) {
                $controller = new Controller\PersonsController();
                $controller->setDocumentManager($serviceLocator->getServiceLocator()->get('doctrine.documentmanager.odm_default'));
                return $controller;
            }
        )
    );
}

现在我想在我的“phpunit”测试中覆盖工厂闭包,如下所示:

$this->getApplicationServiceLocator()->setAllowOverride(true);
    $this->getApplicationServiceLocator()->get('ControllerLoader')->setService('Application\Controller\Persons', function($serviceLocator) {
        $controller = new Controller\PersonsController();
        $controller->setDocumentManager($this->documentManagerMock);
        return $controller;

});

但这只是覆盖了我认为的服务。

有人能帮助我吗?

1 个答案:

答案 0 :(得分:0)

轻松:

$this->getApplicationServiceLocator()->setAllowOverride(true);
$this->getApplicationServiceLocator()->get('ControllerLoader')->setFactory('Application\Controller\Persons', function($serviceLocator) {
        $controller = new Controller\PersonsController();
        $controller->setDocumentManager($this->documentManagerMock);
        return $controller;
};