Laravel - 如何在 phpunit 测试中设置伪造语言环境?

Mar*_*eca 1 phpunit faker laravel

我可以将faker应用程序中的语言环境更改config/app.phppt_BR更改,'faker_locale' => 'pt_BR',并且它在我的工厂中运行良好,但在我的测试用例中运行良好。这就是我在我的测试中导入 faker 的方式:

namespace Tests\Unit;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Models\Proprietario;

class ProprietarioTest extends TestCase
{
    use WithFaker, RefreshDatabase;


    public function testStore(){


        $attributes = [
            'name' => $this->faker->name,
            'email' => $this->faker->email,
            'address' => $this->faker->city,
            'phone' => $this->faker->cellPhoneNumber,
            'municipio' => $this->faker->randomDigit,
        ];
        $response = $this->post('/api/v1/proprietario', $attributes);

        $response->assertStatus(201);
        $createdArea = Proprietario::latest();
        $this->assertDatabaseHas('proprietarios', $attributes);
    }
Run Code Online (Sandbox Code Playgroud)

测试将失败,$this->faker->cellPhoneNumber因为它在默认语言环境中不可用。我正在使用 Laravel 5.8 和 PHP 7.2

Rob*_*ard 6

WithFaker trait 为您提供了一种可以使用的方法

$this->faker('nl_NL')->postcode // dutch postcode
Run Code Online (Sandbox Code Playgroud)

如果您想将它用于所有测试,请在您的测试中覆盖 setupFaker

protected function setUpFaker()
{
    $this->faker = $this->makeFaker('nl_NL');
}
Run Code Online (Sandbox Code Playgroud)