Created
November 3, 2017 08:09
-
-
Save omitobi/43bba09631b3d933a323dffc1be957e5 to your computer and use it in GitHub Desktop.
assertArrayStructure function for testing PHP_Unit in Laravel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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