Mock API Response using Symfony and Behat ❤️

17 / 08 / 2020

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

1- Setup 🔧

I will use Behat and the Symfony HttpClient, you can find the source code here

$ symfony new — full demo-mock-api-response
$ composer require --dev friends-of-behat/symfony-extension:^2.0

2- Configure HttpClient 🔌

# config/packages/framework.yaml
framework:
  http_client:
    scoped_clients:
        githubClient:
            base_uri: 'https://api.github.com'
            headers:
                Accept: 'application/vnd.github.v3+json'
                Authorization: 'token FOO BLABLA%'

3- Logic 💡

For this demonstration the logic is very simple:

  • Make a GET request to the Github API
  • Transform the response as an array viatoArray()
  • Pass the data to User::create to create the User with information from Github

4- Test ✅

Behat is a powerful tool for testing, it uses the Gherkin language. If you don’t know what is Behat and Gherkin you should read the documentation, it’s better to follow this article but in few words you write steps in Gherkin in a file and any step (Given, When, And, Then) corresponds to a function defined in a PHP class suffixed by Context. you can pass argument from the behat file to the PHP class, then in PHP class you do stuff and assertion.

This is the github.feature that ensure we did the job

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

Given The response have the following body
| id     | 42         |
| login  | ismail1432 |

The second step fetch the User from our GithubUserRepository

When I fetch a user with username ismail1432

The third and last step check that the code returns an object User with the information returned by the API.

Now let see our Context file, I named it GithubContext

1- The function theResponseHaveTheFollowingBody corresponds to the first step, we retrieve the data defined in the step, then we mock the response that will be returned by the request (you can see documentation). In the Mock we pass the retrieved data and when we have created our Mock we pass it to our repository.

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

3- Last function, we check that the $user is an instance of AppEntityUser and also check that the information in $user correspond to the informations fetched from the API.

That’s all for this post, stay tuned for others way to test and mock API Response… I hope you liked it, don’t forget to clap. 👏👏🏻👏🏼👏🏽👏🏾👏🏿

Thanks for reading, I hope you liked it, don't forget to share it !
LinkedIn Twitter