Laravel 如何进行范围测试
Laravel how to make Test for Scope
我想在我的统计模型中测试我的示波器 --->
class Statistic extends Model
{
use HasTranslations;
use HasFactory;
public $translatable = ['country'];
protected $guarded = ['id'];
public function scopeFilter($query, array $filters): Builder
{
return $query->when($filters['search'] ?? false, fn ($query, $search) => $query-
>where(DB::raw('lower(country)'), 'like', '%' . strtolower($search) . '%'));
}
}
我该如何组织这个?
如何正确编写功能测试?
这个怎么样:
class StatisticScopesTest extends TestCase
{
/** @test */
public function is_has_a_scope_filter()
{
$this->assertEquals(0, Statistic::count());
$this->assertEquals(0, Statistic::filter(['search' => 'PT'])->count());
Statistic::factory()->create(['country' => 'PT']);
$this->assertEquals(1, Statistic::count());
$this->assertEquals(1, Statistic::filter(['search' => 'PT'])->count());
$this->assertEquals(0, Statistic::filter(['search' => 'EN'])->count());
}
}
- 2 个针对空案例的断言
- 为一个国家创建条目
- 对于一个条目的案例有 3 个断言
我想在我的统计模型中测试我的示波器 --->
class Statistic extends Model
{
use HasTranslations;
use HasFactory;
public $translatable = ['country'];
protected $guarded = ['id'];
public function scopeFilter($query, array $filters): Builder
{
return $query->when($filters['search'] ?? false, fn ($query, $search) => $query-
>where(DB::raw('lower(country)'), 'like', '%' . strtolower($search) . '%'));
}
}
我该如何组织这个?
如何正确编写功能测试?
这个怎么样:
class StatisticScopesTest extends TestCase
{
/** @test */
public function is_has_a_scope_filter()
{
$this->assertEquals(0, Statistic::count());
$this->assertEquals(0, Statistic::filter(['search' => 'PT'])->count());
Statistic::factory()->create(['country' => 'PT']);
$this->assertEquals(1, Statistic::count());
$this->assertEquals(1, Statistic::filter(['search' => 'PT'])->count());
$this->assertEquals(0, Statistic::filter(['search' => 'EN'])->count());
}
}
- 2 个针对空案例的断言
- 为一个国家创建条目
- 对于一个条目的案例有 3 个断言