【问题标题】:Laravel - How to set faker locale in phpunit tests?Laravel - 如何在 phpunit 测试中设置伪造的语言环境?
【发布时间】:2019-07-03 05:21:49
【问题描述】:

我可以将我的应用程序中的faker 区域设置在config/app.php 更改为pt_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);
    }

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

【问题讨论】:

  • 您应该检查一下WithFaker Trait 为您提供的开箱即用的功能。您可能需要在自己的 setUp() 方法中修改 faker 实例。

标签: laravel phpunit faker


【解决方案1】:

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

$this->faker('nl_NL')->postcode // dutch postcode

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

protected function setUpFaker()
{
    $this->faker = $this->makeFaker('nl_NL');
}

【讨论】:

    猜你喜欢
    • 2019-06-26
    • 2019-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    • 2016-02-18
    • 1970-01-01
    相关资源
    最近更新 更多