在布局中使用自定义视图助手时,单元测试失败

时间:2013-03-12 15:27:21

标签: phpunit zend-framework2

所以我创建了自定义视图助手,并在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

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

1 个答案:

答案 0 :(得分:1)

我遇到了同样的问题,我解决的问题不是很好(但是我的具体问题解决了这个问题)。

phpunit测试找不到我的工厂查看助手,但它找到了我的invokables。然后,我做了以下事情:

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

当我使用浏览器时,它使用正确的Factory。当我使用phpunit时,它使用invokables。

当我需要设置一些参数时会发生问题。然后,我设置了一些默认参数,只能由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;
    }

}

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