Laravel provides concise HTTP response mock syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive.
The basic implementation provides a variety of response type shortcuts:
use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' => 204, ]);
This syntax works well in a comprehensive test scenario:
class ApiIntegrationTest extends TestCase { public function test_service_communication() { Http::fake([ // String response 'api.notifications.com/*' => 'Message sent', // Array response (converted to JSON) 'api.products.com/*' => [ 'products' => [ ['id' => 1, 'name' => 'laptop'], ['id' => 2, 'name' => 'Mobile'] ] ], // Status code response 'api.status.com/check' => 200, 'api.deprecated.com/*' => 410, // Different response types of related endpoints 'api.orders.com/active' => ['status' => 'Processing'], 'api.orders.com/error' => 400, 'api.orders.com/message' => 'System is not available' ]); // Test with assertions $response = Http::get('api.notifications.com/send'); $this->assertEquals('Message sent', $response->body()); $products = Http::get('api.products.com/list'); $this->assertCount(2, $products['products']); $status = Http::get('api.status.com/check'); $this->assertTrue($status->successful()); } }
This concise syntax significantly improves the maintainability of tests by reducing the cognitive burden when reading tests, allowing you to focus on business logic rather than HTTP mock details.
The above is the detailed content of Simplified HTTP Response Mocking in Laravel Tests. For more information, please follow other related articles on the PHP Chinese website!