首页 > 解决方案 > PHPUnit 不打开没有“.php”后缀的文件

问题描述

我决定在我的项目中使用 PHPUnit 进行测试。为了做到这一点,我从 Composer 的官方站点安装了 Composer(它是最新版本的 Composer;我提早了一点,以便您可以理解更新 Composer 不会解决问题)并安装了 PHPUnit Composer 在命令行中的帮助。我的composer.json样子是这样的:

{
    "autoload": {
        "classmap": [
            ""
        ]
    },
    "require-dev": {
        "phpunit/phpunit": "^9"
    }
}

我也有phpunit.xml.dist。它看起来像这样:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php">
    <testsuites>
        <testsuite name="Components">
            <directory suffix="Test.php">./tests/components/</directory>
        </testsuite>
    </testsuites>
</phpunit>

正如您从这段代码中看到的那样,我的代码按以下方式组织:

--folderForClasses
--anotherFolderForClasses
--OneMoreFolder
--vendor
   `--autoload.php
--tests
   `--components
         `--TokenGeneratorTest.php
--composer.json
--phpunit.xml.dist

可以执行以下命令:

  1. vendor\bin\phpunit tests
  2. vendor\bin\phpunit tests/components
  3. vendor\bin\phpunit tests/components/TokenGeneratorTest.php
  4. vendor\bin\phpunit --testsuite Components

因为只有一个测试文件,所有这些都会导致以下结果:

PHPUnit 9.0.0 by Sebastian Bergmann and contributors.

...                                                                 3 / 3 (100%)

Time: 00:00.066, Memory: 4.00 MB

OK (3 tests, 3 assertions)

但是,我不能执行如下命令:

  1. vendor\bin\phpunit TokenGeneratorTest
  2. vendor\bin\phpunit tests/components/TokenGeneratorTest

这两个命令导致:

PHPUnit 9.0.0 by Sebastian Bergmann and contributors.

Cannot open file "TokenGeneratorTest".

和:

PHPUnit 9.0.0 by Sebastian Bergmann and contributors.

Cannot open file "tests/components/TokenGeneratorTest".

我在几个教程中看到像最后两个这样的命令应该可以工作,但由于某种原因它们不起作用。这可能是什么原因以及如何使其发挥作用?

提前非常感谢。

标签: phptestingphpunit

解决方案


我不确定您为什么要获得 v9.0.0(您今天应该获得带有该要求的 v9.3.8),但似乎在 v9.0.0 中删除了提供不带扩展名的测试文件名的能力。您正在查看较旧的教程。

来自 8.5.8 的帮助:

PHPUnit 8.5.8 by Sebastian Bergmann and contributors.

Usage:
  phpunit [options] UnitTest [UnitTest.php]
  phpunit [options] <directory>

来自 9.0.0 的帮助:

PHPUnit 9.0.0 by Sebastian Bergmann and contributors.

Usage:
  phpunit [options] UnitTest.php
  phpunit [options] <directory>

推荐阅读