Laravel
Beginner
1 min read
API Testing and JSON Assertions
Example
<?php
// tests/Feature/Api/PostApiTest.php
namespace Tests\Feature\Api;
use App\Models\Post;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class PostApiTest extends TestCase
{
use RefreshDatabase;
private User $user;
protected function setUp(): void
{
parent::setUp();
$this->user = User::factory()->create();
}
public function test_can_list_published_posts(): void
{
Post::factory(3)->published()->create();
$this->actingAs($this->user, 'sanctum')
->getJson('/api/v1/posts')
->assertOk()
->assertJsonStructure([
'data' => [['id', 'title', 'slug', 'status', 'author']],
'links' => ['first', 'last', 'prev', 'next'],
'meta' => ['total', 'per_page', 'current_page'],
])
->assertJsonCount(3, 'data');
}
public function test_returns_404_for_missing_post(): void
{
$this->actingAs($this->user, 'sanctum')
->getJson('/api/v1/posts/9999')
->assertNotFound()
->assertJsonPath('message', 'Resource not found.');
}
public function test_validation_errors_return_422(): void
{
$this->actingAs($this->user, 'sanctum')
->postJson('/api/v1/posts', [])
->assertUnprocessable()
->assertJsonValidationErrors(['title', 'body', 'status']);
}
}
Related Resources
Laravel Reference
Complete tag & property list
Laravel How-To Guides
Step-by-step practical guides
Laravel Exercises
Practice what you've learned
More in Laravel
This is the last lesson in this section.
Create a free account to earn a certificate