如何在ZF2中获取单元测试中的ControllerManager

时间:2015-01-08 13:48:20

标签: php unit-testing zend-framework2

我希望在单元测试中运行dispatch之前将一些依赖项注入控制器。

控制器就像

class WidgetController {
   private $foo;
   public function setFoo ($foo) { $this->foo = $foo; };
   public function barAction () { return array('foo' => $this->foo);  };
}

测试就像

class WidgetControllerTest extends AbstractHttpControllerTestCase {
    function testBarAction ()
    {
       // ERROR HERE - does not get controller, error can't get ControllerManager
       $controller = $this->getApplicationServiceLocator()
            ->get("ControllerManager")
            ->get("MyApp\Controller\WidgetController");


       $controller->setFoo("my injected value");
       $this->dispatch("/my-app/widget/bar");
       $this->assertTrue(
          stristr("my injected value", 
                  $this->getResponse()->getBody()));
    }
}

我不确定如何在运行dispatch之前设置WidgetController::$foo的值;

1 个答案:

答案 0 :(得分:1)

如果您可以访问ApplicationServiceManager中的配置,则可以尝试:

$applicationServiceLocator = $this->getApplicationServiceLocator();
$config = $applicationServiceLocator->get('config');
$config['controllers']['factories']['MyApp\Controller\WidgetController'] = function ($sm) {
    $controller = new \MyApp\Controller\WidgetController();
    // ... do initialization logic
    return $controller;
};
$applicationServiceLocator->setService('config', $config);