繁体   English   中英

PHP 致命错误:在 PHPUnit 6 和 PHP 7.0 中找不到“PHPUnit\\Framework\\TestCase”类

[英]PHP Fatal error: Class 'PHPUnit\Framework\TestCase' not found with PHPUnit 6 and PHP 7.0

我在玩 php 7 和 phpunit 6。这是我写的测试:

<?php declare(strict_types=1);

namespace Test;

use DesignPatterns\Observer\User;
use DesignPatterns\Observer\UserObserver;
use PHPUnit\Framework\TestCase;

class ObserverTest extends TestCase
{
    public function testChangeInUserLeadsToUserObserverBeingNotified()
    {
        $observer = new UserObserver();

        $user = new User();
        $user->attach($observer);

        $user->changeEmail('foo@bar.com');
        $this->assertCount(1, $observer->getChangedUsers());
    }
}

当我尝试运行此测试时,收到以下错误消息:

PHP Fatal error:  Class 'PHPUnit\Framework\TestCase' not found in /home/.../.../Test/ObserverTest.php on line 9

我用 composer 安装了 PHPUnit,这是我的 composer.json 文件内容:

{
    "require": {
        "phpunit/phpunit": "^6.0"
    },
    "autoload": {
        "psr-4": {"DesignPatterns\\": "src/"}
    }
}

根据PHPUnit 6 文档,您的测试现在应该扩展 PHPUnit\\Framework\\TestCase 而不是 PHPUnit_Framework_TestCase。

我知道这不是自动加载的问题。 实际上,如果我用 PHPUnit_Framework_TestCase 替换 PHPUnit\\Framework\\TestCase,它工作得很好,但我想知道为什么这种语法不起作用。

我尝试了一些关于 google、stackoverflow 和 PHPUnit 的 github 存储库的研究,但找不到任何东西。

我期待着你的答案,

编辑

这是我的文件的组织方式:

src/
├── DataMapper
│   ├── StorageAdapter.php
│   ├── UserMapper.php
│   └── User.php
├── Observer
│   ├── UserObserver.php
│   └── User.php
Test/
├── DataMapperTest.php
└── ObserverTest.php

我找到了答案:

我用这个命令行执行我的测试:

phpunit Test/ObserverTest.php

PHPUnit 全局安装在我的计算机上,但它是 5.1.3 版本:

phpunit -v

PHPUnit 5.1.3 by Sebastian Bergmann and contributors.

Runtime:       PHP 7.0.13-0ubuntu0.16.04.1 with Xdebug 2.4.0
Configuration: /home/.../.../DesignPatterns/phpunit.xml

并且语法 PHPUnit\\Framework\\TestCase 仅适用于 PHPUnit 6

现在,如果我运行php vendor/bin/phpunit Test/ObserverTest.php ,它可以完美运行......

如果有人在升级到 Symfony 4.4 / 5.0 后出现此错误,我将发布此信息。

在较新版本的 Symfony 中,您有一个在phpunit.xml.dist定义的phpunit.xml.dist 当你运行./bin/phpunit时会下载这个版本,它的源代码将放在./bin/.phpunit/phpunit-VERSION下。 如果你正在执行php ./bin/console --env=test debug:container你可能会得到 OP 异常提到的。 修复很简单 - 您需要在composer.json添加类的路径:

    "autoload-dev": {
        "psr-4": {
            "App\\Tests\\": "tests/"
        },
        "classmap": [
            "tests/",
            "bin/.phpunit/phpunit-9.2.0-0/src" <--- Make sure the version is correct.
        ]
    },

然后运行composer dump-autoload ,最后php ./bin/console --env=test debug:container应该可以工作。

就我而言,我之前在 /Applications/MAMP/Library/bin 目录中的路径中有一个不同版本的 phpunit。 创建指向全局安装版本 (7.5.1) 而不是 5.1.3 的符号链接后,这为我修复了错误:

cd /Applications/MAMP/Library/bin
mv phpunit phpunit_bak
ln -s /usr/local/bin/phpunit phpunit

以防万一您遇到 PhpStorm 中未找到的PHPUnit\\Framework\\TestCase

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM