Zend framework2 Zend Framework 2控制器插件在单元测试中不可用
您好,我是Zend的新成员,被要求与Z2一起开发。我试图通过控制器插件添加可重用的功能,但在单元测试方面没有成功。它在常规应用程序中工作良好Zend framework2 Zend Framework 2控制器插件在单元测试中不可用,zend-framework2,Zend Framework2,您好,我是Zend的新成员,被要求与Z2一起开发。我试图通过控制器插件添加可重用的功能,但在单元测试方面没有成功。它在常规应用程序中工作良好 // Application\Controller\Plugin\HelloWorld.php namespace Application\Controller\Plugin; use Zend\Mvc\Controller\Plugin\AbstractPlugin; use Zend\Http\Client; use Zend\Http\Reques
// Application\Controller\Plugin\HelloWorld.php
namespace Application\Controller\Plugin;
use Zend\Mvc\Controller\Plugin\AbstractPlugin;
use Zend\Http\Client;
use Zend\Http\Request;
class HelloWorld extends AbstractPlugin
{
public function helloWorld()
{
return "HELLO WORLD";
}
}
// Application\Controller\IndexController.php
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class IndexController extends AbstractActionController
{
public function indexAction()
{
echo $this->helloworld()->helloWorld();
}
}
//Application\config\module.config.php
...
'controller_plugins' => array(
'invokables' => array(
'helloworld' => 'Application\Controller\Plugin\HelloWorld',
),
),
...
我得到的错误是:
Zend\ServiceManager\Exception\ServiceNotFoundException: Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for helloworld
如果为控制器创建单元测试,则在专用的受控单元中测试控制器。您不初始化应用程序,不加载模块,也不解析完整的配置文件 要对控制器进行单元测试,请在
setUp()
方法中添加插件,将其作为可直接在服务管理器中调用的插件。如果您想测试您的配置是否工作,那么您需要进行功能测试。首先尝试引导整个应用程序,然后通过创建请求和断言响应来测试控制器
因为功能测试更难解决,所以从控制器(插件)开始在单元测试中进行测试更容易:
namespace SlmLocaleTest\Locale;
use PHPUnit_Framework_TestCase as TestCase;
use Application\Controller\IndexController;
class IndexControllerTest extends TestCase
{
public function setUp()
{
$controller = new IndexController;
$controller->getPluginManager()
->setInvokableClass('helloworld', 'Application\Controller\Plugin\HelloWorld');
$this->controller = $controller;
}
public function testCheckSomethingHere()
{
$response = $this->controller->indexAction();
}
}
例如,您可以用
setService()
替换setInvokableClass()
,以注入一个mock。这是一个古老的答案,但如果您仍然在Jurian附近,或者其他人找到了这个答案。。。只要调用$this->controller->indexAction(),我想您就麻烦了,因为控制器操作很可能会调用控制器继承自的AbstractActionController类中的某些内容。没有框架初始化,没有工作。不需要是Greg,如果您的索引操作不包含对任何抽象方法的调用,则一切正常。