To write HTTP tests in Laravel, you can use the TestCase
class provided by the Laravel testing framework. Here’s an example of how to write a test for an HTTP GET request to a route:
<?php
namespace Tests\Feature;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function testBasicTest()
{
$response = $this->get('/');
$response->assertStatus(200);
}
}
This test sends a GET request to the /
route and asserts that the status code of the response is 200 (OK).
To test other HTTP methods (such as POST, PUT, and DELETE), you can use the post
, put
, and delete
methods on the TestCase
class, respectively. For example:
$response = $this->post('/users', [
'name' => 'John',
'email' => '[email protected]',
'password' => 'secret',
]);
$response->assertStatus(201); // Created
You can also pass additional request headers and POST data to these methods. For example:
$response = $this->put('/users/1', [
'name' => 'Jane',
], [
'Authorization' => 'Bearer abcdef',
]);
$response->assertStatus(200); // OK
To make assertions on the response body, you can use the assertSee
and assertJson
methods. For example:
$response->assertSee('John');
$response->assertJson([
'name' => 'John',
'email' => '[email protected]',
]);