Home > Backend Development > PHP Tutorial > Simplified HTTP Response Mocking in Laravel Tests

Simplified HTTP Response Mocking in Laravel Tests

Emily Anne Brown
Release: 2025-03-12 17:09:24
Original
494 people have browsed it

Simplified HTTP Response Mocking in Laravel Tests

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,
]);
Copy after login

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());
    }
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template