Php ZF2单元测试中如何获取ControllerManager
在单元测试中运行分派之前,我希望向控制器中注入一些依赖项 控制器就像Php ZF2单元测试中如何获取ControllerManager,php,unit-testing,zend-framework2,Php,Unit Testing,Zend Framework2,在单元测试中运行分派之前,我希望向控制器中注入一些依赖项 控制器就像 class WidgetController { private $foo; public function setFoo ($foo) { $this->foo = $foo; }; public function barAction () { return array('foo' => $this->foo); }; } 考试就像 class WidgetControllerTest
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
的值 如果您有权访问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);