首页 > 解决方案 > Laravel 用更少的数据测试分页

问题描述

我正在尝试缩短测试时间。目前我有一个测试,我需要测试分页链接和元数据。

在我的控制器中,我的分页设置为 15,但是在我的测试中,我必须使用工厂创建 16 个实例才能断言第 2 页上的数据。

TestGetStudents.php

public function testGetStudents() {
    Students::saveMany(factory(Student::class, 16)->make());

    $this->get('url/students/list?page=2')
         ->assertJson([
              'meta' [
                   'current_page' => 2 
              ]
         ]);
}

学生控制器.php

public function list() {
    return Students::paginate();
}

如何编写测试而不必在第二页创建 16 个学生来测试数据?

标签: phplaravellaravel-5

解决方案


替换您的控制器以接收来自用户的分页参数:

public function list(Request $request) {
    $per_page = !($request->input('per_page')) ? 15 : $request->input('per_page');
    return Studentes::paginate($per_page);
}

推荐阅读