Laravel运行php artisan test提示Class 'App\AccountantHelper'未找到如何解决?
报错原因
- 首要原因是新建
App\AccountantHelper类后没有更新Composer自动加载缓存,Laravel的PSR-4自动加载机制无法识别新增的类文件,所以抛出类不存在的错误。 - 类的方法定义和调用不匹配:实际定义的方法名为
Profit,但报错代码中调用的是findProfit,同时方法是普通实例方法,代码中使用了::静态调用,也会引发后续报错。 - 可能存在文件名和类名不匹配的问题:如果app目录下的类文件名和类名大小写、拼写不一致,也会导致自动加载失败。
另外提示的TTY mode is not supported on the Windows platform是Windows平台的正常警告,不影响测试运行,无需处理。
修复步骤
- 刷新Composer自动加载缓存,在项目根目录执行命令:
composer dump-autoload
- 核对类文件名:确认app目录下的类文件命名为
AccountantHelper.php,和类名完全一致,大小写、拼写无错误。 - 修正类方法定义,将方法改为静态,同时和调用的方法名保持一致,修改后的
AccountantHelper.php代码如下:
<?php namespace App; class AccountantHelper { public static function findProfit($amount) { $profitPercent = 10; return $profitPercent * $amount / 100 ; } }
- 核对测试文件的调用逻辑,确保方法名和类中定义的一致,示例测试代码如下:
<?php namespace Tests\Unit; use App\AccountantHelper; use PHPUnit\Framework\TestCase; class AccountantHelperTest extends TestCase { /** @test */ public function it_can_find_profit() { $profit = AccountantHelper::findProfit(100); $this->assertEquals(10, $profit); } }
修改完成后重新执行php artisan test即可正常运行测试。
内容的提问来源于stack exchange,提问作者Abdelrahman Shahin
相关产品推荐
相关产品推荐

