PHP Fatal error: Class not found - PHPUnit

PHP Fatal error: Class not found - PHPUnit

我正在尝试在 PHP 项目中使用 PHPUnit。 这是我的项目结构(文件是斜体字体样式)

我的文件:

composer.json

{
    "require-dev": {
        "phpunit/phpunit":"5.5.4"
    }
}

Pages.php

<?php
namespace controllers

class Pages
{
    public function render()
    {
        return 'Hello World';
    }

}

pagesTest.php

<?php

class PagesTest extends PHPUnit_Framework_TestCase
{
    public function testRenderReturnsHelloWorld()
    {
        $pages = new \controllers\Pages();
        $expected = 'Hello Word';
        $this->assertEquals($expected, $pages->render());
    }
}

当我打开命令行时,我写:

C:\xampp\htdocs\PHPUnitTestProject\vendor\bin>phpunit ../../tests/PagesTest.php

我收到此错误消息:PHP Fatal error: Class 'controllers\Pages' not found in C:\xampp\htdocs\PHPUnitTestProject\tests\pagesTest.php on line 7

这是一个路径问题。我认为这是因为它搜索不存在的 C:\xampp\htdocs\PHPUnitTestProject\vendor\bin\controllers\Pages()
应该是C:\xampp\htdocs\PHPUnitTestProject\controllers\Pages()

从根文件夹调用 phpunit:

$ cd C:\xampp\htdocs\PHPUnitTestProject\
$ vendor\bin\phpunit tests/PagesTest.php

需要指向测试的class,所以在pagesTest.php中添加一个require:

require __DIR__ . "/../controllers/Pages.php";

如果你使用自动加载,那么你可以bootstrap the autoload在你的命令行

phpunit --bootstrap src/autoload.php

你可以设置一个 phpunit.xml 配置文件,就像这个例子(来自我上面链接的 PHPUnit 页面):

<phpunit bootstrap="src/autoload.php">
  <testsuites>
    <testsuite name="money">
      <directory>tests</directory>
    </testsuite>
  </testsuites>
</phpunit>

然后将其与 --configuration 选项一起使用。

phpunit.xml.dist 中添加 bootstrap="vendor/autoload.php" 解决了我的问题。

<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php"> <!-- in here -->
    <php>
        <!-- ... -->
    </php>
    <testsuites>
       <!-- ... -->
    </testsuites>
</phpunit>

尝试 composer dump-autoload -o 命令

我遇到了同样的错误,因为我没有将 Class 命名为与 phpunit 调用的文件名相同的名称。

例如我在打电话:

phpunit TEST_myweb_controller.php

其中有一个 class 定义:class web_controller_test extends PHPUnit\Framework\TestCase

返回错误:Class 'TEST_myweb_controller.php' could not be found in '\my\path\to\tests\TEST_myweb_controller.php'

为了解决这个问题,我将 class 定义更改为:class TEST_myweb_controller extends PHPUnit\Framework\TestCase