【问题标题】:Is it correct to use require/require_once() statement in ZF2 OO PHPUnit test case code?在 ZF2 OO PHPUnit 测试用例代码中使用 require/require_once() 语句是否正确?
【发布时间】:2013-12-24 10:51:51
【问题描述】:

这是一个关于在 Zend Framework 2 中正确编码 PHPUnit 测试的问题,使用面向对象的代码原则。

我有以下 PHPUnit 测试用例:

namespace FedcoUserTest;
use FedcoUser\Controller\MachinistController;

class MachinistControllerTest extends Framework\TestCase
{...}

我的 MachinistController 类是这样的:

namespace FedcoUser\Controller;

class MachinistController extends \ZfcUser\Controller\UserController
{...}

在尝试运行测试用例时,我会收到以下错误:

Debug Error: MachinistController.php - Class 'ZfcUser\Controller\UserController' not found

这很奇怪,因为我的 MachinistController 类运行得很好,并且在作为 Web 应用程序运行时找到了 ZfcUser 的控制器,而不是通过 PHPUnit 测试。

不知何故,我决定放一个

require_once 'vendor/zf-commons/zfc-user/src/ZfcUser/Controller/UserController.php';

插入我的 MachinistControllerTest 类,现在我的 PHPUnit 测试运行没有错误。

我觉得这很奇怪。

为什么:到目前为止,在我使用 ZF2 的经验中,我还没有需要使用 require 函数。 ZF2 是完全 OO 的,那为什么是现在呢?这可能是正确的,但有没有更好的方法,如果有,是什么?

更具体的问题:

  • (正确性)我是否可以在代码中使用此 require_once 行来使测试用例通过?
  • (ZF2 最佳实践)为什么我要在我原本完全 OO ZF2 代码中使用 require_once() 语句(在我看来,使用 require 就像是程序代码的味道)?
  • (OO 最佳实践)为什么在我的 MachinistController 完美扩展 ZfcUser 的控制器时找不到它?

【问题讨论】:

    标签: php zend-framework zend-framework2 phpunit


    【解决方案1】:

    我最终在我的 TestConfiguration.php 文件中的配置中加载了额外的命名空间:

    $additionalNamespaces = array(
        'ZfcUser\Controller' => __DIR__ . '/../../../vendor/zf-commons/zfc-user/src/ZfcUser/Controller/'
    );
    

    很适合我的bootstrap.php,它有以下代码:

    // setup autoloader
    AutoloaderFactory::factory(
        array(
            'Zend\Loader\StandardAutoloader' => array(
                StandardAutoloader::AUTOREGISTER_ZF => true,
                StandardAutoloader::ACT_AS_FALLBACK => false,
                StandardAutoloader::LOAD_NS => $additionalNamespaces,
            )
        )
    );
    

    【讨论】:

      【解决方案2】:

      请不要忘记PHPUnit Tests 不是 ZF2 框架的一部分。 ZF2 不负责在单元测试文件中自动加载类。

      您需要自己模拟类http://phpunit.de/manual/3.6/en/test-doubles.html#test-doubles.mock-objects,并负责自己要求所有类。

      【讨论】:

        【解决方案3】:

        通常,您会在运行测试之前使用 PHPUnit 的引导功能来引导应用程序的某些元素(包括自动加载器)。手册中有一个示例引导程序:http://framework.zend.com/manual/2.0/en/user-guide/unit-testing.html。就我个人而言,我使用了一个稍微修改过的版本,它也引入了 Composer 自动加载器。那么你就不需要在你的测试中使用任何类了。

        【讨论】:

        • 我的bootstrap.php 似乎是一个库存文件,不能更改。相反,TestConfiguration.php 文件似乎要更改。 (bootstrap.php、TestConfiguration.php.dist 和 phpunit.xml)[gist.github.com/dennis-fedco/7881658] 要删除require(),我不知道要更改什么,在哪里更改,以及要留下什么......
        猜你喜欢
        • 2017-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-20
        • 2012-05-02
        • 2014-09-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多