【问题标题】:How to get ControllerManager in Unit Test in ZF2如何在 ZF2 的单元测试中获取 ControllerManager
【发布时间】:2015-03-06 15:47:23
【问题描述】:

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

控制器就像

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()));
    }
}

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

【问题讨论】:

    标签: php unit-testing zend-framework2


    【解决方案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);
    

    【讨论】:

      猜你喜欢
      • 2013-01-25
      • 2014-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多