Skip to content

Instantly share code, notes, and snippets.

@omitobi
Created November 3, 2017 08:09
Show Gist options
  • Save omitobi/43bba09631b3d933a323dffc1be957e5 to your computer and use it in GitHub Desktop.
Save omitobi/43bba09631b3d933a323dffc1be957e5 to your computer and use it in GitHub Desktop.
assertArrayStructure function for testing PHP_Unit in Laravel
<?php
namespace Tests\Unit;
use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function testBasicTest()
{
$collect = collect(['name' => '1', 'detail' => ['age' => 1,'class' => 'abc']]);
$this->assertArraySubset(['name', 'detail' => ['class', 'age']], $collect->toArray());
}
/**
* Assert that the response has a given JSON structure.
*
* @param array $structure
* @param array $arrayData
* @return $this
*/
public function assertArrayStructure(array $structure, array $arrayData)
{
foreach ($structure as $key => $value) {
if (is_array($value) && $key === '*') {
$this->assertInternalType('array', $arrayData);
foreach ($arrayData as $arrayDataItem) {
$this->assertArrayStructure($structure['*'], $arrayDataItem);
}
} elseif (is_array($value)) {
$this->assertArrayHasKey($key, $arrayData);
$this->assertArrayStructure($structure[$key], $arrayData[$key]);
} else {
$this->assertArrayHasKey($value, $arrayData);
}
}
return $this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment