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...