首页 > 解决方案 > 为什么 PHPUnit 看不到 Laravel Facades?

问题描述

我对 PHPUnit 测试和 Laravel 异常有疑问:找不到类 'DB'

我的测试用例文件:

namespace Tests;

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;
}

我的 CreatesApplication 文件:

namespace Tests;

use Illuminate\Contracts\Console\Kernel;

trait CreatesApplication
{
    public function createApplication()
    {
        $app = require __DIR__.'/../bootstrap/app.php';

        $app->make(Kernel::class)->bootstrap();

        return $app;
    }
}

这是我的测试:

namespace Tests\Unit;

use App\Services\RepetitionService;
use PHPUnit\Framework\TestCase;

class RepetitionServiceTest extends TestCase
{
   public function testGetNextIteration()
   {
       $repetitionService = new RepetitionService;

       $nextIteration = $repetitionService->getNextIteration(1);
       $this->assertEquals(2, $nextIteration);
   }
}

正在测试的方法:

public function getNextIteration(int $lastIteration) : int
    {
        // some example code (method is not real but code below copied from original method)
        \DB::table('cards')->get();
        Config::get('params.repeat_iterations');
        config('params.repeat_iterations');
    }

表彰: php vendor/phpunit/phpunit/phpunit --configuration phpunit.xml tests/Unit

版本: laravel 7 PHP 7.4 PHPUnit 9

标签: laravelphpunit

解决方案


尝试从此路径使用数据库

use Illuminate\Support\Facades\DB;

推荐阅读