【问题标题】:Unit tests failing when I use a custom view helper in the layout当我在布局中使用自定义视图助手时单元测试失败
【发布时间】:2013-03-12 15:27:21
【问题描述】:

所以我创建了我的自定义视图助手并在 layout.phtml 中使用它,如下所示:

<?php echo $this->applicationBar(); ?>

它在浏览器中运行完美,但我之前运行的单元测试现在失败了:

1) UnitTests\Application\Controller\IndexControllerTest::testIndexActionCanBeAccessed
Zend\ServiceManager\Exception\ServiceNotFoundException: Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for applicationBar

当我在布局文件中注释掉视图助手时,测试再次通过。

【问题讨论】:

    标签: phpunit zend-framework2


    【解决方案1】:

    我有同样的问题,我解决的方法不是很好(但它解决了我的具体问题)。

    phpunit 测试没有找到我的工厂视图助手,但它正在找到我的可调用对象。然后,我做了以下事情:

    public function getViewHelperConfig() {
        return array(
            'factories' => array(
                'aplicationBar' => function($service) {
                    $applicationBar = new ApplicationBar();
                    return $applicationBar;
                },
            ),
            'invokables' => array(
                'applicationBar' => 'Application\View\Helper\ApplicationBar',
            ),
        );
    

    当我使用浏览器时,它使用正确的工厂。当我使用 phpunit 时,它使用可调用对象。

    当我需要设置一些参数时会出现问题。然后,我设置了一些默认参数,这些参数仅供 phpunit 使用。

    namespace Application\View\Helper;
    
    use Zend\View\Helper\AbstractHelper;
    
    class ApplicationBar extends AbstractHelper {
    
        protected $parameter;
    
        public function __construct($parameter = 'something') {
            $this->parameter = $parameter;
        }
    
        public function __invoke() {
            return $this->parameter;
        }
    
    }
    

    这不是最好的解决方案,但如果我以更好的方式解决它,我会在这里发布。

    【讨论】:

    • 不错。你能发帖吗?我真的不喜欢我的解决方案,我来这里是为了更好的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2019-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多