Quick fixture data and mocking external APIs

Posted: 2014-12-01 02:31:01

We are using a number of external APIs on a project (Pusher, Iron.io, Github, Saucelabs etc). Github is key as we are using it to store and retrieve files from for editing on the site. When running phpunit it is easy to mock these Classes but when running behat tests or protractor we had to do to things to make it possible to mock the tests and not hit the external APIs.

Swapping out Providers

Using Laravel's config/app.php settings we can easily swap out providers for different environments. For example config/testing/app.php could register my GithubMock class.

The GithubMock class just extends the real Github Service but overrides the methods that I do not want to really call out to Github eg create file, update file etc.

That is super easy but now how to return good data.

Quick Fixtures

I made a Facade package called Fixturizer https://github.com/alfred-nutile-inc/fixturizer

You can see in the readme.md how to use it to quickly write and read fixture data that you can get from any of these requests. Then when it is the turn of the mocked provider to return the results it just loads up this fixture and you are set. (PHP VCR is another option as well)

One example

    public function tokens($path)
    {
        $this->logMock('tokens');
        $files = FixturizerReader::getFixture('github_token_show.yml', $this->path);
        return $files;
    }

The method overrides the parent class (the real provider) "tokens" and returns the needed fixture info. I log it as well so I can double check the status of it.

Now the tests not only run faster but are less fragile since sometimes the services would timeout.


Tags:

laravel php