Latest

Thursday, July 6, 2017

Laravel Testing - How to validate each fields in JSON response

Asked by: xmhafiz


I want to test my endpoint with valid format. For example, I have /api/token (POST) which will return api token.

In my case, this endpoint will return "token" string and "message" fields. Thus, I want to check if this two fields are exist with valid format. Currently I am using Laravel Validator.

Example json output:

{
"message": "login successful",
"token": "d4zmendnd69u6h..."
}

Test class (ApiTokenTest.php).

class ApiTokenTest extends TestCase
{

    protected $validFormBody = [
        'os_type' => 'android',
        'device_id' => '0000-AAAA-CCCC-XXXX',
        'os_version' => '5.1',
        'apps_version' => '1.0',
    ];

    public function testSucessResponseFormat()
    {
        $response = $this->json('post', '/api/token', $this->validFormBody);

        $validator = Validator::make(json_decode($response->getContent(), true), [
            'token' => 'required|size:100', // token length should be 100 chars
            'message' => 'required',
        ]);

        if ($validator->fails()) {
            $this->assertTrue(false);
        }
        else {
            $this->assertTrue(true);
        }
    }

}

The issue here is the failure message is not really helps, especially if I have more than 1 fields that are not in valid format, should i assert one-by-one?. (see below phpunit output on failure case). What should I use in order to validate format for each fields? Thanks in advance.

There was 1 failure:

1) Tests\Feature\ApiTokenTest::testSucessResponseFormat
Failed asserting that false is true.


Source

No comments:

Post a Comment

Adbox