Gujarat Santana Gujarat Santana - 4 months ago 10
JSON Question

How to test random value in JsonArray using phpunit

Hello Everyone I'm trying to test API and get the specific json element from the response, here is the response from the API :

{
"Error": null,
"Data": {
"AuthToken": "jaskdfjlsadkfjasd",
"InactiveTimeout": 20
}
}


since the value of AuthToken is always random I can't test it using this code :

$this->post('/login',
[
'id'=>'1',
'password'=>'secret',
])->seeJson([
"Error" => null,
'Data'=>array(
'AuthToken'=>'',
'InactiveTimeout'=>20)
]);


and I've tried using this code :

$this->post('/login',
[
'id'=>'1',
'password'=>'secret',
])->seeJson([
"Error" => null,
'Data'=>array(
'InactiveTimeout'=>20)
]);


but I can't pass the test, my question is how to write test for this case?
Thanks for your help.

Answer

You can try the code below:

$this->post('/login', [
        'id' => '1',
        'password' => 'secret',
    ])
    ->seeJson([
        'Error' => null
    ])
    ->seeJsonStructure([
        'Data' => [
            'AuthToken'
        ]
    ]);