Home >Backend Development >PHP Tutorial >How to unit test in PHP array pagination?
PHP array paging unit testing guide includes: testing edge cases (empty array, invalid page number); testing whether the paging results are correct (first page, middle page, last page); testing whether the total page number calculation is correct (the number of elements is equal to The number of elements per page, the number of elements is greater than the number of elements per page).
PHP Array Paging Unit Testing Guide
Preface
Array paging is a This is a common operation that is often encountered in development. In order to ensure the correctness of the paging functionality, it is very important to perform unit testing. This article will guide you on how to write unit tests for PHP array paging, including practical examples.
Practical case
Suppose we have an array $items
, which needs to be paginated and display 10 elements on each page. Pagination function paginate()
is as follows:
function paginate(array $items, int $page = 1, int $perPage = 10): array { $totalPages = ceil(count($items) / $perPage); if ($page < 1) { $page = 1; } elseif ($page > $totalPages) { $page = $totalPages; } $offset = ($page - 1) * $perPage; return array_slice($items, $offset, $perPage); }
Unit test
$this->assertEquals([], paginate([]));
$this->assertEquals([], paginate([], -1)); $this->assertEquals([], paginate([], 11, 10));
$items = range(1, 100); $this->assertEquals([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], paginate($items));
$this->assertEquals([51, 52, 53, 54, 55, 56, 57, 58, 59, 60], paginate($items, 6));
$this->assertEquals([91, 92, 93, 94, 95, 96, 97, 98, 99, 100], paginate($items, 10));
$items = range(1, 10); $this->assertEquals(1, paginate($items, 1, 10));
$items = range(1, 100); $this->assertEquals(10, paginate($items, 1, 10));
The above is the detailed content of How to unit test in PHP array pagination?. For more information, please follow other related articles on the PHP Chinese website!