【问题标题】:Test Laravel Repository Pattern Database Refreshed When Call The Method调用方法时刷新测试 Laravel 存储库模式数据库
【发布时间】:2021-04-10 20:24:34
【问题描述】:

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

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();
    }
}

【问题讨论】:

  • 您也可以共享 UserRepository 吗?
  • 我更新了它.. 只是一个简单的过滤器当我调用该方法时,表上的记录被刷新并使其为空,它应该返回任何数据。

标签: laravel testing phpunit repository


【解决方案1】:

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

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

这样,你可以代替$this-&gt;seedingDb()

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 2019-03-23
    • 1970-01-01
    • 2014-03-15
    • 2015-06-15
    • 1970-01-01
    相关资源
    最近更新 更多