You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel分页测试优化:减少测试数据量以缩短测试耗时

优化分页测试,减少不必要的实例创建

嘿,我完全懂你的困扰——为了验证第二页的元数据,就得硬生生创建16个Student实例,不仅冗余还拖慢测试速度。这里有几个实用方案帮你把测试耗时砍下来:

方案1:临时修改测试环境的分页条数

Laravel允许在测试中临时覆盖模型的分页配置,不用改动全局设置,就能用更少的实例触发第二页:

public function testGetStudents() {
    // 临时把Student的每页显示条数改成1
    Student::setPerPage(1);
    // 现在只需要2个实例就能触发第二页
    Students::saveMany(factory(Student::class, 2)->make());
    
    $this->get('url/students/list?page=2')
         ->assertJson([
             'meta' => [
                 'current_page' => 2
             ]
         ]);
    // 测试结束后恢复原配置,避免影响其他测试用例
    Student::setPerPage(null);
}

如果你的模型没用到setPerPage方法,也可以直接修改配置项:

// 临时把全局分页条数改成1
config(['pagination.per_page' => 1]);

方案2:模拟分页响应,完全跳过数据库操作

要是你只关心元数据的断言,甚至不用创建任何数据库实例,直接模拟控制器的分页返回结果就行:

use Mockery;

public function testGetStudents() {
    // 模拟分页器对象,返回预设的元数据
    $mockPaginator = Mockery::mock(\Illuminate\Pagination\LengthAwarePaginator::class);
    $mockPaginator->shouldReceive('toArray')
                  ->andReturn([
                      'data' => [],
                      'meta' => [
                          'current_page' => 2,
                          // 按需添加其他必填元数据字段
                      ]
                  ]);
    
    // 让Student模型的paginate方法返回这个模拟对象
    Student::shouldReceive('paginate')
           ->andReturn($mockPaginator);
    
    $this->get('url/students/list?page=2')
         ->assertJson([
             'meta' => [
                 'current_page' => 2
             ]
         ]);
}

这个方案速度最快,完全绕开了数据库读写,适合只验证响应结构的场景。

方案3:请求时动态指定per_page参数(如果API支持)

如果你的分页接口允许通过per_page参数调整每页条数,直接在请求里带上这个参数就好:

public function testGetStudents() {
    // 只需要创建1个实例
    Students::saveMany(factory(Student::class, 1)->make());
    
    $this->get('url/students/list?page=2&per_page=1')
         ->assertJson([
             'meta' => [
                 'current_page' => 2,
                 'per_page' => 1
             ]
         ]);
}

这个方案最灵活,不用改配置也不用模拟,前提是你的控制器已经支持处理per_page请求参数。


内容的提问来源于stack exchange,提问作者Tom Headifen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:12:14