Test an API Pagination feature with PHPUnit

Submitted by Mahmoud_Zalt - 8 years ago

Dynamically testing and Pagination feature in a Restful API

    public function testPaginatingGetAllAccounts()
    {
        // get the current pagination limit from the .env
        $currentPaginationLimit = env('PAGINATION_LIMIT', 10);
        // how much data to add to the pagination limit (will create "limit + x" records in the
        // database to test if "x" will be returned when requesting the "second page")
        $additionalData = 1;
        // the data size to be created ("limit + x")
        $dataSize = $currentPaginationLimit + $additionalData;

        // get the logged in user (create one if no one is logged in)
        $user = $this->getLoggedInTestingUser();

        // create "limit + x" number of fake Accounts
        factory(Account::class, $dataSize)->create()->each(function ($account) use ($user) {
            $account->user_id = $user->id;
            $account->save();
        });

        $queryParameters = 'page=2';

        // send the HTTP request
        $response = $this->apiCall($this->endpoint . '?' . $queryParameters, 'get'); // this is a custom function. you can use $this->get(...)

        // check response status is correct
        $this->assertEquals($response->getStatusCode(), '200');

        // convert JSON response string to Array
        $responseArray = json_decode($response->getContent());

        // assert the second page returned the "x" additional data
        $this->assertEquals(count($responseArray->data), $additionalData);
    }