我正在玩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 documentation,您的测试现在应该扩展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
答案 0 :(得分:14)
我找到了答案:
我用这个命令行解决了我的测试:
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
,它就能完美运行......
答案 1 :(得分:2)
以防您遇到.gitignore
在PhpStorm中找不到的情况,
在项目的根目录运行PHPUnit\Framework\TestCase
,它将下载所有需要的类,并且PhpStorm错误应该消失
答案 2 :(得分:1)
你可以运行./vendor/bin/phpunit Test/ObserverTest.php
它对我有效。
答案 3 :(得分:1)
如果要有人升级到Symfony 4.4 / 5.0之后出现错误,我将发布此消息。
在较新版本的Symfony中,您具有在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
。
答案 4 :(得分:0)
在我的情况下,我在/ 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