Skip to content

Commit d93dbd9

Browse files
author
Andy Soell
committed
Initial commit
0 parents  commit d93dbd9

File tree

3 files changed

+81
-0
lines changed

3 files changed

+81
-0
lines changed

README.md

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# TestResponse::assertJsonStructureMissing
2+
3+
The `TestResponse::assertJsonStructureMissing` assertion works just like [TestResponse::assertJsonStructure](https://laravel.com/api/5.6/Illuminate/Foundation/Testing/TestResponse.html#method_assertJsonStructure), except that it tests for the absence of a particular structure.
4+
5+
```
6+
$response = $this->get('/data');
7+
$response->assertJsonStructureMissing([
8+
'data' => [
9+
'related' => [
10+
'*' => [
11+
'attribute',
12+
],
13+
],
14+
],
15+
]);
16+
```
17+
18+
Full credit for this package goes to [Behzad Shabani](https://github.com/behzadsh). This package just takes his [pull request](https://github.com/laravel/framework/pull/20435) and packages it up so it's super easy to add to your Laravel application.

composer.json

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
{
2+
"name": "amsoell/assert-json-structure-missing",
3+
"description": "Laravel PHPUnit assertion to test for lack of a given JSON structure",
4+
"authors": [
5+
{
6+
"name": "Andy Soell",
7+
"email": "[email protected]"
8+
}
9+
],
10+
"minimum-stability": "dev",
11+
"require": {},
12+
"autoload": {
13+
"psr-4": {
14+
"Amsoell\\AssertJsonStructureMissing\\": "src/"
15+
}
16+
},
17+
"extra": {
18+
"laravel": {
19+
"providers": [
20+
"Amsoell\\AssertJsonStructureMissing\\ServiceProvider"
21+
]
22+
}
23+
}
24+
}

src/ServiceProvider.php

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<?php
2+
3+
namespace Amsoell\AssertJsonStructureMissing;
4+
5+
use Illuminate\Foundation\Testing\TestResponse;
6+
7+
class ServiceProvider extends \Illuminate\Support\ServiceProvider
8+
{
9+
public function boot()
10+
{
11+
TestResponse::macro('assertJsonStructureMissing', function (array $structure = null, $responseData = null) {
12+
if (is_null($structure)) {
13+
return $this->assertJson($this->json());
14+
}
15+
16+
if (is_null($responseData)) {
17+
$responseData = $this->decodeResponseJson();
18+
}
19+
20+
foreach ($structure as $key => $value) {
21+
if (is_array($value) && $key === '*') {
22+
\PHPUnit\Framework\Assert::assertInternalType('array', $responseData);
23+
24+
foreach ($responseData as $responseDataItem) {
25+
$this->assertJsonStructureMissing($structure['*'], $responseDataItem);
26+
}
27+
} elseif (is_array($value)) {
28+
\PHPUnit\Framework\Assert::assertArrayHasKey($key, $responseData);
29+
30+
$this->assertJsonStructureMissing($structure[$key], $responseData[$key]);
31+
} else {
32+
\PHPUnit\Framework\Assert::assertArrayNotHasKey($value, $responseData);
33+
}
34+
}
35+
36+
return $this;
37+
});
38+
}
39+
}

0 commit comments

Comments
 (0)