Laravel 8 测试:PHPUnit 错误:未知格式化程序“唯一”

Jar*_*ler 3 phpunit laravel

我编写了一个涉及工厂的测试。当我执行测试时,我收到此错误:

为 Tests\Unit\ExampleTest::testTakePlace 指定的数据提供程序无效。InvalidArgumentException:未知格式化程序“唯一”/var/www/html/api/vendor/fakerphp/faker/src/Faker/Generator.php:249

预期结果

不应显示此错误,我应该能够使用$this->faker->unique().

我如何尝试解决这个问题

通过一遍又一遍地阅读文档(没有发现任何差异)并阅读互联网上的问题和答案(只找到一个问题和一个答案:扩展 Laravel,TestCase但官方文档,正如我提到的,恰恰相反)。(Laravel 的TestCase由 提供use Illuminate\Foundation\Testing\TestCase;

问题

为什么它不起作用以及如何修复这个错误?

来源

测试源

它扩展了PHPUnit\Framework\TestCase(不是 Laravel 的TestCase),因为文档说要扩展它。事实上: https: //laravel.com/docs/8.x/testing#creating-and-running-tests。这并不是文档中提到扩展它的唯一部分。

<?php

namespace Tests\Unit;

use PHPUnit\Framework\TestCase;
use App\Models\Project;

class ExampleTest extends TestCase
{
    /**
     * @dataProvider provideTakePlaceData
     */
    public function testTakePlace($project)
    {
        $response = $this->json('GET', '/controllerUserProject_takePlace', [
            'project_id' => $project->id
        ]);

        
    }
    
    public function provideTakePlaceData() {
        return [    
                    Project::factory()->make()
        ];
    }
}
Run Code Online (Sandbox Code Playgroud)

控制器

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class ControllerUserProject extends Controller
{
    public function takePlace(Request $request, $project_id)
    {
        return;
    }
}
Run Code Online (Sandbox Code Playgroud)

最重要的是:工厂

<?php

namespace Database\Factories;

use App\Models\Project;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class ProjectFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Project::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
                    'id' => $this->faker->unique()->numberBetween(1, 9000), 
        ];
    }
}
Run Code Online (Sandbox Code Playgroud)

Ama*_*ade 11

改成
use PHPUnit\Framework\TestCase;

use Tests\TestCase;

为什么?

当您的ExampleTest扩展PHPUnit\Framework\TestCaseLaravel 应用程序从未在测试中初始化时,因此您无法访问工厂等 Laravel 功能。

文档告诉您要扩展PHPUnit\Framework\TestCase;,但它指的是单元测试。功能测试应该扩展Tests\TestCase。这是相当新的事情。Tests\TestCase在 Laravel 5.8 之前,单元测试和功能测试都默认扩展。我个人只是将所有测试定义为功能测试以避免此类问题。