Category: PHP, api

This article is the first of a series that will discuss about different ways to test classes that use an external API. As a developer, you have surely been asked to deal with APIs and as a good developer you ALWAYS tests your code, the problem is that in a test environment, there is no external API and you can’t do real HTTP request, I will, therefore, discuss different ways of simulating an API response and test this feature with Behat and Symfony. Suppose you’ve been asked to fetch data of a user from the Github API and return a User object with these data.

In the first step, I pass the response that will be returned when the code will call the API.

In the function iFetchAUserWithUsername we call the repository and the method findByUsername that fetch data and create the User from data, we assign the User to a variable $user that will be used in the last step Last function, we check that the $user is an instance of App\Entity\User and also check that the information in $user correspond to the informations fetched from the API.
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners