From 790e78a29c8a33827c9aa64136ab555e98416898 Mon Sep 17 00:00:00 2001 From: Jason McCreary Date: Mon, 30 Sep 2019 06:57:48 -0600 Subject: [PATCH] [6.x] Add assertNoContent to TestResponse (#30125) * Add assertNoContent to TestResponse * Update TestResponse.php --- .../Foundation/Testing/TestResponse.php | 15 ++++++ .../Foundation/FoundationTestResponseTest.php | 48 +++++++++++++++++++ 2 files changed, 63 insertions(+) diff --git a/src/Illuminate/Foundation/Testing/TestResponse.php b/src/Illuminate/Foundation/Testing/TestResponse.php index 10f1f2350975..6d3f985c1165 100644 --- a/src/Illuminate/Foundation/Testing/TestResponse.php +++ b/src/Illuminate/Foundation/Testing/TestResponse.php @@ -89,6 +89,21 @@ public function assertOk() return $this; } + /** + * Assert that the response has the given status code and no content. + * + * @param int $status + * @return $this + */ + public function assertNoContent($status = 204) + { + $this->assertStatus($status); + + PHPUnit::assertEmpty($this->getContent(), 'Response content is not empty.'); + + return $this; + } + /** * Assert that the response has a not found status code. * diff --git a/tests/Foundation/FoundationTestResponseTest.php b/tests/Foundation/FoundationTestResponseTest.php index 48cdd7f0a7f6..bf9df7ea47ad 100644 --- a/tests/Foundation/FoundationTestResponseTest.php +++ b/tests/Foundation/FoundationTestResponseTest.php @@ -194,6 +194,54 @@ public function testAssertUnauthorized() $response->assertUnauthorized(); } + public function testAssertNoContentAsserts204StatusCodeByDefault() + { + $statusCode = 500; + + $this->expectException(AssertionFailedError::class); + + $this->expectExceptionMessage("Expected status code 204 but received {$statusCode}"); + + $baseResponse = tap(new Response, function ($response) use ($statusCode) { + $response->setStatusCode($statusCode); + }); + + $response = TestResponse::fromBaseResponse($baseResponse); + $response->assertNoContent(); + } + + public function testAssertNoContentAssertsExpectedStatusCode() + { + $statusCode = 500; + $expectedStatusCode = 418; + + $this->expectException(AssertionFailedError::class); + + $this->expectExceptionMessage("Expected status code {$expectedStatusCode} but received {$statusCode}"); + + $baseResponse = tap(new Response, function ($response) use ($statusCode) { + $response->setStatusCode($statusCode); + }); + + $response = TestResponse::fromBaseResponse($baseResponse); + $response->assertNoContent($expectedStatusCode); + } + + public function testAssertNoContentAssertsEmptyContent() + { + $this->expectException(AssertionFailedError::class); + + $this->expectExceptionMessage('Response content is not empty'); + + $baseResponse = tap(new Response, function ($response) { + $response->setStatusCode(204); + $response->setContent('non-empty-response-content'); + }); + + $response = TestResponse::fromBaseResponse($baseResponse); + $response->assertNoContent(); + } + public function testAssertStatus() { $statusCode = 500;