Since I had problems trying to implement the method "seeJsonStructure" as you will see here: phpunit error "must be a array or ArrayAccess" -> laravel/framework#18280
I just wanted and alternative to check the keys of the json that I receive from the Laravel API that I created.
The things to pay atention on "composer.json" are:
...
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
}
},
...
on "tests/Traits/ApiTestTrait.php":
...
public function validateKeys($actualData, $expectedData)
{
foreach ($actualData as $key => $value) {
if (is_array($value)){
$this->validateKeys($value, $expectedData);
} else {
$this->assertContains($key, $expectedData);
}
}
}
public function validateCountKeys($actualData, $expectedData)
{
$this->assertCount(count($expectedData), $this->getKeys($actualData));
}
private function getKeys($actualData)
{
$keys = array();
foreach ($actualData as $key => $value) {
if (is_array($value)){
$keys = array_merge($keys, $this->getKeys($value, $keys));
} elseif (!array_key_exists($key, $keys)){
$keys[] = $key;
}
}
return array_unique($keys);
}
...
Just a little clarification about these methods:
"validateKeys" -> it will recursively iterate a multidimensional array evaluating each "key" with "value" different from an array. If the "value" is an array then we can evaluate the "keys" of "value" and not the "key" itself.
"validateCountKeys" -> It will give us all the keys of a multidimentional array where the value of a key is not an array. After getting all the keys I just do "array_unique" for eliminating duplicated items.
on "tests/api/UserControllerTest.php":
...
use Tests\Traits\ApiTestTrait;
...
use ApiTestTrait;
...
$this->validateKeys($paginatedUsers, $paginationAndUserKeys);
$this->validateCountKeys($paginatedUsers, $paginationAndUserKeys);
...
I encourage you to help me if you think this could have been done in a different way.