PHP code example of missionx-co / laravel-better-http-fake

1. Go to this page and download the library: Download missionx-co/laravel-better-http-fake library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

missionx-co / laravel-better-http-fake example snippets


class Service {
    public function createInstance($data) {
        return $this->client()->post('/instances', $data)->json();
    }

    public function client(): PendingRequest {
        return Http::baseUrl('https://service.com')
            ->withToken(config('services.service.api_key'));
    }
}

Http::fake([
    'https://service.com/instances' => Http::response(['key' => 'value'], 204)
]);

(new Service)->createInstance(['bodyKey' => 'bodyValue']);

Http::assertSent(function($request) {
    return $request->url() == "https://service.com/instances" &&
           $request->method() == 'POST' &&
           $request->data() == ['bodyKey' => 'bodyValue'];
});

(new Service)->client()
    ->shouldMakePostRequestTo('instances')
    ->withData(['bodyKey' => 'bodyValue'])  // Verify payload
    ->andRespondWith(['key' => 'value']);   // Fake response

(new Service)->createInstance($body);  // Execute

->doNotAssertSent();  // Only fake the response, skip checks

->andRespondWithSequence(
    Http::sequence([
        Http::response([]),  // First response
        Http::response([]),  // Second response
    ])
);

->withHeaders(['Header-Key' => 'Header-Value']);  // Verify headers

->withFile('photo', 'profile.jpg');  // Verify file uploads

// GET Request
->shouldMakeGetRequestTo('users/1')
// PUT Request
->shouldMakePutRequestTo('users/1')
// PATCH Request
->shouldMakePatchRequestTo('profile')
// DELETE Request
->shouldMakeDeleteRequestTo('posts/123')