PHPUnit class 未找到测试用例

PHPUnit class TestCase not found

我正在创建一个 PHP 库并想开始编写测试。我收到一个错误 Fatal error: Class 'PHPUnit\Framework\TestCase' not found

我的项目结构是:在我的主目录中有 composer.json,一个包含我所有 类 的 src/ 目录,一个包含 unit/ 和 acceptance/ 子目录的 tests/ 目录。我尝试 运行 的测试在 unit/ 目录中。我正在使用命令行界面进行 运行 测试,因此在 运行ning phpunit tests/unit/testMyClass.php

时会发生错误

testMyClass.php 看起来像:

<?php
require 'vendor/autoload.php';
use PHPUnit\Framework\TestCase;

class MyClassTest extends TestCase {
    public function testCreateMyClass() {
        // Tests are written here
    }
}
?>

我的 composer.json 是:

{
    "require-dev": {
        "phpunit/phpunit": "4.8.*"
    }
    "autoload": {
        "classmap": [
            "src/"
        }
    }
}

我遇到了同样的问题,我通过从 PHPUnit_Framework_TestCase class 扩展我的测试 class 而不是使用 命名空间PHPUnit\Framework\TestCase。重建你的项目结构后,它对我来说工作得很好。

tests/unit/testMyClass.php

<?php
require './vendor/autoload.php';

class MyClassTest extends PHPUnit_Framework_TestCase {
     public function testCreateMyClass() {
        // Tests are written here
     }
}
?>

composer.json

{
   "name": "root/project",
   "authors": [
      {
           "name": "watzerm",
           "email": "some.email@provider.at"
      }
   ],
   "require": {
       "phpunit/phpunit": "5.4.*"
   },
   "autoload": {
       "classmap": [
           "src/"
       ]
   }
}

结果

$./vendor/bin/phpunit tests/unit/testMyClass.php

PHPUnit 4.8.27 by Sebastian Bergmann and contributors.

.

Time: 252 ms, Memory: 2.25MB

OK (1 test, 0 assertions)

请告诉我这是否也适合您!

我用较新版本的 PHPUnit 解决了这个问题:

wget https://phar.phpunit.de/phpunit-6.0.phar
php phpunit-6.0.phar -c app/

输出:

PHPUnit 6.0.10 by Sebastian Bergmann and contributors.

..                                                                  2 / 2 (100%)

Time: 486 ms, Memory: 14.00MB

OK (2 tests, 3 assertions)

这适用于 Symfony 2.8 LTS 和 PHPunit 6.0 github repo - https://github.com/nikola-bodrozic/PHPUnit-Symfony28

我解决了我的问题:

extends PHPUnit\Framework\TestCase

您需要 运行 php bin/phpunit 在项目的根目录,它将下载所有需要的 类 并且 PhpStorm 错误应该消失了

确保项目根目录中存在“phpunit.xml”文件。在这个文件中必须有一个带有“bootstrap =”供应商/autoload.php”属性的“phpunit”标签。
像 :

<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
     bootstrap="vendor/autoload.php"
     colors="true">

就我而言,它解决了问题。