调用方法时刷新测试 Laravel 存储库模式数据库

问题描述

我想测试存储库方法的返回输出。但是当我调用方法时,数据库突然刷新。但是当我尝试不调用存储库方法并调试它有记录的表时。这是我的代码,我错过了什么吗?

use App\Repositories\UserRepository;

class ExampleTest extends TestCase
{
    protected $repository;

    protected function setUp(): void
    {
        parent::setUp();

        $this->repository = app(UserRepository::class);
    }
    
    public function it_should_return_empty_when_no_filter_found()
    {
        $this->seedingDb();

        $response = $this->repository->filter(); // When i call this the record on table return empty

        dd($response); // Result empty
    }
    
    private function seedingDb()
    {
        for ($i = 0; $i < 5; $i++) {
            User::create([
                'name'          => $this->faker->word,'role'          => $this->faker->word,'property_name' => $this->faker->word,'email'         => $this->faker->email,'phone_number'  => $this->faker->phoneNumber,'password'      => $this->faker->word,'status'        => 'active',]);
        }
    }
}

用户存储库:

use App\Repositories\UserRepository;

class UserRepository
{
    public function filter()
    {
        return User::whereStatus('active')->get()->toArray();
    }
}

解决方法

User::create() 方法可能返回错误。

尝试按照此处所述创建模型工厂:https://laravel.com/docs/8.x/database-testing#defining-model-factories

这样,您可以代替 $this->seedingDb()

$users = User::factory()->count(5)->make();