簡體   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