Courses

Testing in Laravel 11: Advanced Level

Testing Third-Parties with HTTP Fake

Summary of this lesson:
- Use Http::fake() to simulate API responses
- Test external service interactions
- Create mock HTTP responses
- Verify API request handling
- Simulate external service behavior

This is where we get to kind of more "advanced" faking of stuff, which is faking external services/APIs.

This is probably the most tricky part of testing, and I get a lot of questions about it. So, how do you fake an external service?

There are three ways, which we will discuss in the upcoming three lessons:

  • HTTP fake
  • Mocking Classes
  • Using Sandbox/Test Environments

For the first one, let's examine the example from an open-source monicahq/monica project.


HTTP Fake Example

As you can see in the example below, the Http::fake() is used, similar to the examples from previous lessons about other Laravel Facades.

class GetGPSCoordinateTest extends TestCase
{
// ...
 
/** @test */
public function it_gets_gps_coordinates()
{
$body = file_get_contents(base_path('tests/Fixtures/Services/Address/GetGPSCoordinateSampleResponse.json'));
Http::fake([
'fake.com/v1/*' => Http::response($body, 200),
]);
 
$address = Address::factory()->create();
 
$request = [
'address_id' => $address->id,
];
 
(new GetGPSCoordinate($request))->handle();
 
$address->refresh();
 
$this->assertDatabaseHas('addresses', [
'id' => $address->id,
'latitude' => '34.0736204',
'longitude' => '-118.4003563',
]);
 
$this->assertInstanceOf(
Address::class,
$address
);
}
 
// ...
}

Now, what does this test do?

First, it gets...

The full lesson is only for Premium Members.
Want to access all 31 lessons of this course? (74 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord