R
R
Ramm2018-05-25 11:03:47
PHPUnit
Ramm, 2018-05-25 11:03:47

How to properly test applications that request third-party APIs?

The project has a SomethingApi.php class that has methods for requesting a third-party service (getting data, editing, etc.).
This class is used mainly in queues (Jobs), you need to write tests for these tasks.
My solution:
1. Create a class like MockSomethingApi.php , whose methods will return static JSON, without actually calling the API, then inject this class into Jobs..

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
seriogja, 2018-07-20
@seriogja

Good afternoon!
You don't need to create a separate mock class. Laravel comes out of the box with a Mockery package and a wrapper above it. Therefore, you can mock an object partially (usually the api calls themselves), while the rest of the methods continue to work without changes.
Inside the test:

$client = factory(Client::class)->create();
$mock = Mockery::mock(Client::class);
$this->app->instance($class, $mock);
$mock->shouldReceive('createFromApi')
            ->withAnyArgs()
            ->andReturn($client);

In this example, the createFromApi method of the Client class is mocked (which, let's say, creates an instance based on the data of the API call). Now, by specifying andReturn($client), we know for sure that an instance of the Client class will be returned. All other methods remain unchanged.
$this->app->instance installs a "tweaked" instance when resolving from DI. In this way, you are mocking specific API methods that are called within your test.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question