使用Composer和autoload.php在PHPUnit中自动加载类

时间:2013-03-29 19:46:53

标签: php namespaces phpunit autoload composer-php

我刚刚通过Composer安装了Sebastian Bergmann的PHPUnit版本3.7.19,并编写了一个我想要进行单元测试的课程。

我希望我的所有课程都自动加载到每个单元测试中,而必须在我的测试顶部使用includerequire,但这证明是难!

这就是我的目录结构(尾随/斜杠表示目录,而不是文件):

  • composer.json
  • composer.lock
  • composer.phar
  • LIB /
    • returning.php
  • 测试/
    • returningTest.php
  • 供应商/
    • 仓/
      • PHPUnit的
    • 作曲/
    • 的PHPUnit /
    • 的symfony /
    • autoload.php

我的 composer.json 文件包含以下内容:

"require": {
    "phpunit/phpunit": "3.7.*",
    "phpunit/phpunit-selenium": ">=1.2"
}

我的 returning.php 类文件包含以下内容:

<?php
class Returning {
    public $var;
    function __construct(){
        $this->var = 1;
    }
}
?>

我的 returningTest.php 测试文件包含以下内容:

<?php
class ReturningTest extends PHPUnit_Framework_TestCase
{
    protected $obj = null;

    protected function setUp()
    {
        $this->obj = new Returning;
    }

    public function testExample()
    {   
        $this->assertEquals(1, $this->obj->var);
    }

    protected function tearDown()
    {

    }
}
?>

但是,当我从命令行运行./vendor/bin/phpunit tests时,出现以下错误:

  

PHP致命错误:未找到“返回”类   第8行的/files/code/php/db/tests/returningTest.php

我注意到composerautoload.php中生成了vendor/autoload.php个文件,但不确定这是否与我的问题相关。

此外,在Stack Overflow的其他一些答案中,人们已经提到过在编写器中使用PSR-0和在PHP中使用namespace命令,但我没有成功使用任何一个。

请帮忙!我只是想在PHPUnit中自动加载我的类,所以我可以使用它们创建对象而不必担心includerequire


更新:2013年8月14日

我现在已经创建了一个名为PHPUnit Skeleton的开源项目,以帮助您轻松启动并运行PHPUnit测试,以便为您的项目。

5 个答案:

答案 0 :(得分:71)

嗯,起初。你需要告诉自动加载器在哪里找到类的php文件。这是通过遵循PSR-0标准来完成的。

最好的方法是使用命名空间。当您请求Acme/Tests/ReturningTest.php课程时,自动装带器会搜索Acme\Tests\ReturningTest文件。有一些很棒的命名空间教程,只是搜索和阅读。请注意,命名空间是而不是用于自动加载的PHP内容,它可用于自动加载。

Composer附带标准PSR-0自动加载器(vendor/autoload.php中的自动加载器)。在您的情况下,您想告诉自动装带器搜索lib目录中的文件。然后,当您使用ReturningTest时,它会查找/lib/ReturningTest.php

将此添加到您的composer.json

{
    ...
    "autoload": {
        "psr-0": { "": "lib/" }
    }
}

the documentation中的更多信息。

现在自动加载器可以找到你需要的类,让PHPunit知道在运行测试之前有一个文件要执行:一个bootstrap文件。您可以使用--bootstrap选项指定引导程序文件的位置:

$ ./vendor/bin/phpunit tests --bootstrap vendor/autoload.php

然而,使用PHPunit configuration file

更好
<!-- /phpunit.xml.dist -->
<?xml version="1.0" encoding="utf-8" ?>
<phpunit bootstrap="./vendor/autoload.php">

    <testsuites>
        <testsuite name="The project's test suite">
            <directory>./tests</directory>
        </testsuite>
    </testsuites>

</phpunit>

现在,您可以运行该命令,它将自动检测配置文件:

$ ./vendor/bin/phpunit

如果将配置文件放入另一个目录,则需要使用-c选项将该目录的路径放在命令中。

答案 1 :(得分:40)

[ Update2 ]另一种更简单的替代方法是在autoload-devreference)中使用composer.json指令。好处是你不需要维护两个bootstrap.php(一个用于prod,一个用于dev),只是为了自动加载不同的类。

{
  "autoload": {
    "psr-4": { "MyLibrary\\": "src/" }
  },
  "autoload-dev": {
    "psr-4": { "MyLibrary\\Tests\\": "tests/" }
  }
}

[更新] Wouter J的答案更完整。但是我可以帮助想要在tests/文件夹中设置PSR-0自动加载的人 Phpunit使用此模式*Test.php扫描所有文件。所以我们不需要自己加载它们。但是我们仍然希望在tests/下自动加载其他支持类,例如fixture / stub或一些父类。

一种简单的方法是查看Composer项目本身如何设置phpunit测试。它实际上非常简单。请注意&#34; bootstrap&#34;。

的行

参考:https://github.com/composer/composer/blob/master/phpunit.xml.dist

<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="tests/bootstrap.php"
>
    <testsuites>
        <testsuite name="Composer Test Suite">
            <directory>./tests/Composer/</directory>
        </testsuite>
    </testsuites>

    <groups>
        <exclude>
            <group>slow</group>
        </exclude>
    </groups>

    <filter>
        <whitelist>
            <directory>./src/Composer/</directory>
            <exclude>
                <file>./src/Composer/Autoload/ClassLoader.php</file>
            </exclude>
        </whitelist>
    </filter>
</phpunit>

参考:https://github.com/composer/composer/blob/master/tests/bootstrap.php

<?php

/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

error_reporting(E_ALL);

$loader = require __DIR__.'/../src/bootstrap.php';
$loader->add('Composer\Test', __DIR__);

上面的最后一行是在命名空间Composer \ Test下自动加载phpunit测试类。

答案 2 :(得分:6)

这些答案都不是我想要的。是PHPUnit加载测试文件,但不加载存根/固定装置。 Chaun Ma的回答没有删除它,因为运行vendor/bin/phpunit已经包含自动加载,所以没有办法让自动加载器的实例在那时将更多路径推送到它的堆栈。

我最终在文档中找到了这个:

  

如果您需要在多个目录中搜索相同的前缀,那么   可以将它们指定为数组:

{
    "autoload": {
        "psr-0": { "Monolog\\": ["src/", "lib/"] }
    }
}

答案 3 :(得分:1)

有一种 非常简单 的方法,可以通过自动加载和引导来设置phpunit。使用phpunit的--generate-configuration选项在几秒钟内创建您的phpunit.xml配置 -:

vendor/bin/phpunit --generate-configuration

(如果在您的PATH中设置了phpunit,则仅需phpunit --generate-configuration)。此选项已在phpunit5及更高版本中提供。

此选项将提示您输入引导文件( vendor / autoload.php ),测试和源目录。如果您的项目使用composer默认设置(请参见下面的目录结构),则默认选项就是您所需要的。只需按下RETURN 3次!

project-dir
   -- src
   -- tests
   -- vendor

您会得到一个默认的phpunit.xml,它很好用。当然,您可以进行编辑以包含您需要的任何专业知识(例如colors="true"):

<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/8.1/phpunit.xsd"
         bootstrap="vendor/autoload.php"
         executionOrder="depends,defects"
         forceCoversAnnotation="true"
         beStrictAboutCoversAnnotation="true"
         beStrictAboutOutputDuringTests="true"
         beStrictAboutTodoAnnotatedTests="true"
         verbose="true">
    <testsuites>
        <testsuite name="default">
            <directory suffix="Test.php">tests</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">src</directory>
        </whitelist>
    </filter>
</phpunit>

答案 4 :(得分:0)

如果您使用的是PHPUnit 7,则可以从src/文件夹中创建类,以自动加载以下测试:

  1. 确保您的composer.json文件看起来与此类似:

    {
        "autoload": {
            "classmap": [
                "src/"
            ]
        },
        "require-dev": {
            "phpunit/phpunit": "^7"
        }
    }
    
  2. 要在composer.json运行命令中应用更改

    composer install
    
  3. 最后,您可以在tests/文件夹中运行测试:

    ./vendor/bin/phpunit tests/
    
相关问题