PHPUnit 测试中 Zend Framework 3 中的模拟视图助手

Mock view helper in Zend Framework 3 in PHPUnit test

我想在 Zend Framework 3 中测试一个特定的控制器操作。因为我使用 ZfcUser (https://github.com/ZF-Commons/ZfcUser) and Bjyauthorize (https://github.com/bjyoungblood/BjyAuthorize) 我需要模拟一些视图助手。例如,我需要模拟 isAllowed 查看助手并让它 return 始终为真:

class MyTest extends AbstractControllerTestCase
{
    public function setUp()
    {
        $this->setApplicationConfig(include 'config/application.config.php');
        $bootstrap      = \Zend\Mvc\Application::init(include 'config/application.config.php');
        $serviceManager = $bootstrap->getServiceManager();

        $viewHelperManager = $serviceManager->get('ViewHelperManager');

        $mock = $this->getMockBuilder(IsAllowed::class)->disableOriginalConstructor()->getMock();
        $mock->expects($this->any())->method('__invoke')->willReturn(true);

        $viewHelperManager->setService('isAllowed', $mock);

        $this->getApplication()->getServiceManager()->setAllowOverride(true);
        $this->getApplication()->getServiceManager()->setService('ViewHelperManager', $viewHelperManager);
    }

    public function testViewAction()
    {
        $this->dispatch('/myuri');
        $resp = $this->getResponse();
        $this->assertResponseStatusCode(200);
        #$this->assertModuleName('MyModule');
        #$this->assertMatchedRouteName('mymodule/view');
    }
}

在我的 view.phtml 中(将由 opening/dispatching /myuri uri 呈现)我调用视图助手 $this->isAllowed('my-resource').

但是我在执行 testViewAction() 时得到了响应代码 500,失败异常:

Exceptions raised:
Exception 'Zend\ServiceManager\Exception\ServiceNotFoundException' with message 'A plugin by the name "isAllowed" was not found in the plugin manager Zend\View\HelperPluginManager' in ../vendor/zendframework/zend-servicemanager/src/AbstractPluginManager.php:131

如何以某种方式将我的 isAllowed 模拟注入视图助手管理器,让测试用例 (testViewAction / $this->dispatch()) 通过。

ViewHelperManager 是服务管理器的另一个实例。并且不允许覆盖 source code。你能在 "setService" 方法之前尝试 "setAllowOverride" 吗?

如前一个答案所述,我们需要在应用程序对象的 ViewHelperManager 中覆盖 ViewHelper。以下代码显示了如何实现这一点:

public function setUp()
{
    $this->setApplicationConfig(include 'config/application.config.php');
    $bootstrap = \Zend\Mvc\Application::init(include 'config/application.config.php');
    $serviceManager = $bootstrap->getServiceManager();

    // mock isAllowed View Helper of Bjyauthorize
    $mock = $this->getMockBuilder(IsAllowed::class)->disableOriginalConstructor()->getMock();
    $mock->expects($this->any())->method('__invoke')->willReturn(true);

    // inject the mock into the ViewHelperManager of the application
    $this->getApplication()->getServiceManager()->get('ViewHelperManager')->setAllowOverride(true);
    $this->getApplication()->getServiceManager()->get('ViewHelperManager')->setService('isAllowed', $mock);
}