ProductApiTest.php
tests/Feature/ProductApiTest.php
Feature Test for Product API Endpoints
This feature test class verifies the full API lifecycle for Product resources, including creation, validation, retrieval, updating, and deletion. It uses Laravel's RefreshDatabase and WithFaker traits to ensure a clean test environment and realistic data.
Features:
• Tests all RESTful endpoints: index, store, show, update, destroy
• Validates response structure, status codes, and resource formatting
• Checks database state after each operation
• Asserts custom resource properties and error handling
Complete Implementation
<?php namespace Tests\Feature; use Tests\TestCase; use App\Models\Product; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\WithFaker; class ProductApiTest extends TestCase { use RefreshDatabase, WithFaker; // Refresh database before each test, use Faker for dummy data /** * Test getting a list of products (index endpoint) with Resource formatting. * @return void */ public function testCanFetchProductsListWithResourceFormatting() { // Arrange: Create 5 dummy products in the database using the factory Product::factory()->count(5)->create(); // Act: Make an HTTP GET request to the products index endpoint $response = $this->getJson('/api/products'); // Assert: Verify the response structure, status, and data $response->assertStatus(200) // HTTP 200 OK ->assertJsonStructure([ // Check the overall JSON structure 'success', 'message', 'data' => [ '*' => [ // Each item in the 'data' array 'id', 'name', 'description', 'price', 'stock', 'created_at', 'updated_at', 'status_code', // From ProductResource::with() 'custom_message', // From ProductResource::with() ] ], 'meta' => [ // Pagination metadata 'current_page', 'per_page', 'total', 'last_page', 'from', 'to', ] ]) ->assertJson([ // Assert specific top-level values 'success' => true, 'message' => 'Products retrieved successfully.', ]) ->assertJsonCount(5, 'data'); // Assert exactly 5 products are returned in 'data' // Assert a specific property from the `with()` method for the first item $response->assertJsonPath('data.0.status_code', 200); $response->assertJsonPath('data.0.custom_message', 'Product data successfully retrieved.'); } /** * Test creating a new product (store endpoint) with valid data. * @return void */ public function testCanCreateProductWithResourceFormatting() { // Arrange: Prepare valid product data $productData = [ 'name' => $this->faker->unique()->word . ' New Product', // Ensure unique name 'description' => $this->faker->sentence, 'price' => $this->faker->randomFloat(2, 1, 1000), 'stock' => $this->faker->numberBetween(0, 500), ]; // Act: Make an HTTP POST request to create a product $response = $this->postJson('/api/products', $productData); // Assert: Verify the response $response->assertStatus(201) // HTTP 201 Created ->assertJson([ 'success' => true, 'message' => 'Product created successfully.', 'data' => [ 'name' => $productData['name'], 'price' => (float) number_format($productData['price'], 2, '.', ''), // Assert formatted price 'stock' => (int) $productData['stock'], // Assert formatted stock ] ]); // Assert properties from `with()` method $response->assertJsonPath('data.status_code', 200); $response->assertJsonPath('data.custom_message', 'Product data successfully retrieved.'); // Assert the product was saved in the database $this->assertDatabaseHas('products', [ 'name' => $productData['name'], 'price' => $productData['price'], ]); } /** * Test validation for creating a product with invalid data. * @return void */ public function testCannotCreateProductWithInvalidData() { // Arrange: Prepare invalid product data (missing required field, invalid type) $invalidProductData = [ 'description' => 'Some description', 'price' => -10, // Invalid: price cannot be negative 'stock' => 'abc', // Invalid: stock must be integer ]; // Act: Make an HTTP POST request with invalid data $response = $this->postJson('/api/products', $invalidProductData); // Assert: Verify validation errors $response->assertStatus(422) // HTTP 422 Unprocessable Entity ->assertJsonValidationErrors(['name', 'price', 'stock']) // Assert specific fields have validation errors ->assertJson([ 'message' => 'The name field is required. (and 2 more errors)', // Laravel's default validation summary 'errors' => [ 'name' => ['The name field is required.'], 'price' => ['The price must be at least 0.'], 'stock' => ['The stock field must be an integer.'], ] ]); // Assert the product was NOT saved in the database $this->assertDatabaseMissing('products', [ 'description' => 'Some description', // A unique field to check for absence ]); } /** * Test fetching a single product (show endpoint). * @return void */ public function testCanFetchSingleProductWithResourceFormatting() { // Arrange: Create a specific product in the database $product = Product::factory()->create(); // Act: Make an HTTP GET request for the specific product $response = $this->getJson('/api/products/' . $product->id); // Assert: Verify the response $response->assertStatus(200) ->assertJson([ 'success' => true, 'message' => 'Product retrieved successfully.', 'data' => [ 'id' => $product->id, 'name' => $product->name, 'description' => $product->description, 'price' => (float) number_format($product->price, 2, '.', ''), 'stock' => (int) $product->stock, ] ]); // Assert properties from `with()` method $response->assertJsonPath('data.status_code', 200); $response->assertJsonPath('data.custom_message', 'Product data successfully retrieved.'); } /** * Test fetching a non-existent product. * @return void */ public function testCannotFetchNonExistentProduct() { // Act: Make an HTTP GET request for a non-existent ID $response = $this->getJson('/api/products/9999'); // Assuming 9999 does not exist // Assert: Verify 404 Not Found due to Route Model Binding failure $response->assertStatus(404); // Note: Laravel's default 404 response for models might be just 'Not Found'. // You can customize this in `app/Exceptions/Handler.php`. } /** * Test updating an existing product (update endpoint). * @return void */ public function testCanUpdateProductWithResourceFormatting() { // Arrange: Create a product to update $product = Product::factory()->create(); $updateData = [ 'name' => 'Updated Product Name', 'price' => 999.99, 'stock' => 50, 'description' => 'Updated description test.' ]; // Act: Make an HTTP PUT request to update the product $response = $this->putJson('/api/products/' . $product->id, $updateData); // Assert: Verify the response $response->assertStatus(200) ->assertJson([ 'success' => true, 'message' => 'Product updated successfully.', 'data' => [ 'id' => $product->id, 'name' => $updateData['name'], 'price' => (float) number_format($updateData['price'], 2, '.', ''), 'stock' => (int) $updateData['stock'], ] ]); // Assert properties from `with()` method $response->assertJsonPath('data.status_code', 200); $response->assertJsonPath('data.custom_message', 'Product data successfully retrieved.'); // Assert the database was updated $this->assertDatabaseHas('products', [ 'id' => $product->id, 'name' => $updateData['name'], 'price' => $updateData['price'], 'stock' => $updateData['stock'], ]); } /** * Test deleting a product (destroy endpoint). * @return void */ public function testCanDeleteProduct() { // Arrange: Create a product to delete $product = Product::factory()->create(); // Act: Make an HTTP DELETE request to delete the product $response = $this->deleteJson('/api/products/' . $product->id); // Assert: Verify the response $response->assertStatus(200) // Or 204 No Content for successful deletion with no content ->assertJson([ 'success' => true, 'message' => 'Product deleted successfully.' ]); // Assert the product was removed from the database $this->assertDatabaseMissing('products', [ 'id' => $product->id, ]); } }
💡
Key Features
• Full-stack feature testing for Product API
• Validates both API responses and database state
• Ensures resource formatting and custom properties
• Covers all CRUD and validation scenarios