As a developer, I often find myself working on applications that interact with third-party APIs or external services. While it's essential to test such integrations, depending on real external services during testing can introduce delays, flakiness, or even unexpected costs. That’s why mocking HTTP requests is such a powerful concept in testing.

Today, I want to introduce you to a fantastic PHP package, aksoyih/http-mock. This package allows you to easily mock HTTP requests and responses, enabling you to test your application's behavior without relying on actual API calls. Let me walk you through its features and show you how to use it.

How to Get Started

To get started, you can install the package via Composer:

composer require --dev aksoyih/http-mock

Then, you can use it like:

use Aksoyih\HttpMock\HttpMock;

require_once  'vendor/autoload.php';
$mock = new HttpMock();

Why?

aksoyih/http-mock provides a straightforward way to create mock HTTP responses during testing. It integrates seamlessly with PHPUnit and supports flexible configuration, making it an excellent choice for developers who want to simulate HTTP interactions.

Here are some benefits of using this package:

  1. Isolation: Test your application's logic without depending on real APIs.
  2. Speed: Avoid delays caused by network requests.
  3. Reliability: Eliminate test flakiness due to external factors.
  4. Customizability: Define specific responses, including status codes, headers, and body content.

Examples

$mock->when('GET', 'https://api.example.com/user')
    ->willReturn(['id' => 1, 'name' => 'John']);
    
$response = $mock->getMockResponse('GET','https://api.example.com/user');
$mock->when('POST', 'https://api.example.com/user')
    ->withStatus(201)
    ->withHeaders(['Content-Type' => 'application/json'])
    ->willReturn(['message' => 'Created']);

$response = $mock->getMockResponse('POST', 'https://api.example.com/user');
$mock->withDelay(100);
$mock->when('GET', 'https://api.example.com/delayed')
    ->willReturn(['data' => 'delayed']);
    
$response = $mock->getMockResponse('GET', 'https://api.example.com/delayed');

Wrapping Up

aksoyih/http-mock is a lightweight yet powerful tool for testing HTTP interactions in PHP. Its simplicity and flexibility make it an excellent choice for developers aiming to build robust and reliable applications.

If you’re working with APIs in your project, give this package a try. You’ll be surprised how much easier it makes testing your code. For more details, check out the official repository or its Packagist page.

Happy testing! 🚀

http-mock

A PHP library for mocking HTTP clients with customizable responses and behaviors