If you are used to TDD, you will definitely come across this at some point. Mocking an API client like Guzzle is a piece of cake in Laravel.
As a test case, I want to mock a Guzzle call to get data from a certain endpoint.
I will simply do the following
- Import the following classes into your test class.
use Mockery;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Response;
- Create a mockery object.
$mock = Mockery::mock(Client::class);
NOTE:- the Client class is Guzzle Class.
- Create a response variable.
$response = json_encode(['data'=>'ok']);
NOTE:- The array should contain the expected response you want.
- Now define what the mock object should do.
$mock->shouldReceive('get')->once()->andReturn(new Response(200,[],$response));
- Finally, bind the mock object to an instance of the Guzzle client class.
$this->app->instance('GuzzleHttp\Client', $mock);
After following these steps, anywhere you instantiate Guzzle class in your code will automatically call the mock object instead.
Do you have other ideas about mocking API calls ?, feel free to comment.
Ciao !
Top comments (0)