Laravel如何为范围做测试



我想在我的统计模型中测试我的作用域——>

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 assertion for empty case
  • 创建国家条目
  • 一个条目的情况下的3个断言

最新更新