0

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.

1 Answer 1

1

It looks like you are not displaying anything in the terminal if there is in fact any validation errors, what you can do is a var_dump into the terminal if the validator fails, like so:

    if ($validator->fails()) {
        var_dump($validator->errors()->all());
        $this->assertTrue(false);
    }
    else {
        $this->assertTrue(true);
    }
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the idea. i come out with fwrite(STDERR, print_r($validator->errors()->all(), true)); for properly showing the output

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.