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

时间:2018-01-19 14:10:03

标签: unit-testing mocking zend-framework3 view-helpers zend-servicemanager

我想测试Zend Framework 3中的特定控制器操作。因为我使用ZfcUserhttps://github.com/ZF-Commons/ZfcUser)和Bjyauthorizehttps://github.com/bjyoungblood/BjyAuthorize)我需要模拟一些视图助手。例如,我需要模拟isAllowed视图助手并让它始终返回true:

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(将通过打开/发送/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()模拟注入视图助手管理器。

2 个答案:

答案 0 :(得分:1)

如上一个答案中所述,我们需要覆盖应用程序对象中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);
}

答案 1 :(得分:0)

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

相关问题