diff --git a/src/Illuminate/Testing/AssertableJsonString.php b/src/Illuminate/Testing/AssertableJsonString.php index 8819315ec7a0..92962fa55d5d 100644 --- a/src/Illuminate/Testing/AssertableJsonString.php +++ b/src/Illuminate/Testing/AssertableJsonString.php @@ -3,6 +3,7 @@ namespace Illuminate\Testing; use ArrayAccess; +use Closure; use Countable; use Illuminate\Contracts\Support\Jsonable; use Illuminate\Support\Arr; @@ -219,7 +220,11 @@ public function assertMissingExact(array $data) */ public function assertPath($path, $expect) { - PHPUnit::assertSame($expect, $this->json($path)); + if ($expect instanceof Closure) { + PHPUnit::assertTrue($expect($this->json($path))); + } else { + PHPUnit::assertSame($expect, $this->json($path)); + } return $this; } diff --git a/tests/Testing/TestResponseTest.php b/tests/Testing/TestResponseTest.php index e054a875a68e..887ba4a0516b 100644 --- a/tests/Testing/TestResponseTest.php +++ b/tests/Testing/TestResponseTest.php @@ -827,6 +827,27 @@ public function testAssertJsonPathCanFail() $response->assertJsonPath('0.id', '10'); } + public function testAssertJsonPathWithClosure() + { + $response = TestResponse::fromBaseResponse(new Response([ + 'data' => ['foo' => 'bar'], + ])); + + $response->assertJsonPath('data.foo', fn ($value) => $value === 'bar'); + } + + public function testAssertJsonPathWithClosureCanFail() + { + $response = TestResponse::fromBaseResponse(new Response([ + 'data' => ['foo' => 'bar'], + ])); + + $this->expectException(AssertionFailedError::class); + $this->expectExceptionMessage('Failed asserting that false is true.'); + + $response->assertJsonPath('data.foo', fn ($value) => $value === null); + } + public function testAssertJsonFragment() { $response = TestResponse::fromBaseResponse(new Response(new JsonSerializableSingleResourceStub));