Skip to content

Commit

Permalink
[8.x] Add bad request test response assertion
Browse files Browse the repository at this point in the history
Inspired by PR laravel#38553.  A readability enhancement in the same manner.
Just like `assertOk`, `assertUnauthorized` and company this adds an
`assertBadRequest` to ensure that a [400 Bad Request](https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.1) was sent
in the response.

The intention is to increase readability and add broader support to the
existing suite of response code assertions which are much easier to
understand.

This introduces no breaking changes since it does not modify any
existing methods.

Also introduced a test case for the assert error path and the path where
there is no assertion error.
  • Loading branch information
timmartin19 committed Sep 1, 2021
1 parent cf58af1 commit cff40e6
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/Illuminate/Testing/TestResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,16 @@ public function assertUnprocessable()
return $this->assertStatus(422);
}

/**
* Assert that the response has a 400 Bad Request status code.
*
* @return $this
*/
public function assertBadRequest()
{
return $this->assertStatus(400);
}

/**
* Assert that the response has the given status code.
*
Expand Down
30 changes: 30 additions & 0 deletions tests/Testing/TestResponseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -488,6 +488,36 @@ public function testAssertUnprocessable()
$response->assertUnprocessable();
}

public function testAssertBadRequestWhenNotBadRequest()
{
$statusCode = 500;

$this->expectException(AssertionFailedError::class);

$this->expectExceptionMessage('Expected response status code');

$baseResponse = tap(new Response, function ($response) use ($statusCode) {
$response->setStatusCode($statusCode);
});

$response = TestResponse::fromBaseResponse($baseResponse);
$response->assertBadRequest();
}

public function testAssertBadRequestWhenIsBadRequest()
{
$statusCode = 400;

$baseResponse = tap(new Response, function ($response) use ($statusCode) {
$response->setStatusCode($statusCode);
});

$response = TestResponse::fromBaseResponse($baseResponse);
$chainedResponse = $response->assertBadRequest();
// Ensure that we can chain the response and implicitly that we do _not_ throw an assertion error
$this->assertEquals($response, $chainedResponse);
}

public function testAssertNoContentAsserts204StatusCodeByDefault()
{
$statusCode = 500;
Expand Down

0 comments on commit cff40e6

Please sign in to comment.