jeudi 6 février 2020

How to test API with codeception and iterate over attributes?

I want to write a test for an API in Laravel 6 by using codeception.

Normally when you want to test the required attributes you have to write a public function like this:

    // returns a raw valid employee
    private function getRawData($arr = []){
        $obj = [
            'localPersonalId' => '66002200',
            'firstName' => 'Mamal',
            'lastName' => 'Amrikai',
            'dateOfBirth' => '1970-06-15',
            'dateOfJoin' => '2010-10-17',
            'genderId' => 'd',
            'locationTypeId' => 's'
        ];
        foreach($arr as $key => $value){
            $obj[$key] = $value;
        }
        return $obj;
    }

    /**
     * @param ApiTester $I
     */
    private function authenticatedUserFailedCreateEmployeeUsingEmptyFirstname(ApiTester $I)
    {
        $I->wantToTest('Authenticated super user failed create employee using empty firstname');

        // set request header
        $I->amBearerAuthenticated($this->token);

        $data = $this->getRawData(['firstname' => '']);

        // send request employee data
        $I->sendPOST('employees', $data);

        // check response code is 422 unprocessable entity
        $I->seeResponseCodeIs(422);
    }

Now I want to make authenticatedUserFailedCreateEmployeeUsingEmptyFirstname a little bit more general to receive an attribute and repeat this test for each attribute. Something like this:

    /**
     * @param ApiTester $I
     */
    public function authenticatedUserFailedCreateEmployeeUsingEmptyAttributes(ApiTester $I)
    {
        $I->wantToTest('Authenticated super user failed create employee using empty attributes:');

        $requiredAttributes = ['localPersonalId', 'firstName', 'lastName', 'genderId', 'locationTypeId'];

        foreach($requiredAttributes as $attr){
            $this->authenticatedUserFailedCreateEmployeeUsingEmptyAttribute($I, $attr);
        }
    }

    /**
     * @param ApiTester $I
     */
    private function authenticatedUserFailedCreateEmployeeUsingEmptyAttribute(ApiTester $I, $attributeName)
    {
        $I->wantToTest('Authenticated super user failed create employee using empty ' . $attributeName);

        // set request header
        $I->amBearerAuthenticated($this->token);

        $data = $this->getRawData([$attributeName => '']);

        // send request employee data
        $I->sendPOST('employees', $data);

        // check response code is 422 unprocessable entity
        $I->seeResponseCodeIs(422);
    }

But this does not work and only does the test for the first attribute in the list that is localPersonalId. How can I reach this goal? It seems I need to instantiate ApiTester $I for each case.

Aucun commentaire:

Enregistrer un commentaire