gpt4 book ai didi

Laravel - 如何在 PHPUnit 测试中使用 faker?

转载 作者:行者123 更新时间:2023-12-03 10:52:20 27 4
gpt4 key购买 nike

当我运行测试时,它给了我这个错误:

undefined variable $faker.



这是 WithFaker 文件。

https://github.com/laravel/framework/blob/5.5/src/Illuminate/Foundation/Testing/WithFaker.php
<?php

namespace Tests\Unit;

use App\User;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;

class LoginTest extends TestCase
{

use WithFaker;

/**
* A basic test example.
*
* @return void
*/

/** @test */
public function test_example()
{

$user = User::create([
'username' => $faker->firstName(),
]);

}

}

最佳答案

您必须使用 $this->faker->firstName()不只是 $faker->firstName() 更新 1
现在当我们使用 WithFaker特质 $this->faker会给我们null ,要解决这个问题,请务必调用 $this->setupFaker()第一的。
例如

class SomeFactory
{
use WithFaker;

public function __construct()
{
$this->setUpFaker();
}

}
信用@Ebi

关于Laravel - 如何在 PHPUnit 测试中使用 faker?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50318048/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com