gpt4 book ai didi

php - 如何在 laravel 中模拟 DB 门面?

转载 作者:行者123 更新时间:2023-12-04 01:57:06 26 4
gpt4 key购买 nike

我正在编写我的单元测试,默认情况下它们不应该访问数据库。
按照一般规则,我总是使用 eloquent 来获得结果,但是一些更复杂的查询我必须使用原始数据库

我有这个功能:

public function GetPassword($email)
{
$result = DB::table('vin_user_active')
->select(
"vin_user_active.id",
"vin_user_active.password",
DB::raw('COALESCE(
vin_user_active.pass_update_date <=
CURRENT_TIMESTAMP -
INTERVAL vin_org_active.password_expiration_days DAY, 0
) AS password_expired')
)
->join('vin_org_active', "vin_user_active.org", "=", "vin_org_active.id")
->where("email", "=", $email)
->first();

return $result;
}

现在我在 mock GetPassword 函数,但是
1.我认为函数应该是私有(private)的,而不是公开的。
2. 覆盖率仅为 %50,因为跳过了整个功能。

我将如何 mock 它?现在我有这个
$this->db =Mockery::mock('Illuminate\Database\Query\Builder')->makePartial();

DB::shouldReceive('table')
->once()
->with("vin_user_active")
->andReturn($this->db);

DB::shouldReceive('raw')
->once()
->with(Mockery::any())
->andReturn(true);

DB::shouldReceive('select')
->once()
->with("vin_user_active.id,
vin_user_active.password,
DB::raw('COALESCE(
vin_user_active.pass_update_date <=
CURRENT_TIMESTAMP -
INTERVAL vin_org_active.password_expiration_days DAY, 0
) AS password_expired'")
->andReturn($this->db);

老实说,我不知道自己在做什么,我从来没有 mock 过这么多级别的函数调用。

任何的想法?

最佳答案

其实很简单

    DB::shouldReceive("raw")
->set('query', 'query test')
->andReturn(true);

关于php - 如何在 laravel 中模拟 DB 门面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35001878/

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