Contract Testing

Posted: 2016-05-27 10:47:39

Sometimes we need to make sure external APIs have not changed. Some of those we have control over some of those we do not.

Either way we can run tests daily, weekly or as needed, outside of our tests we run with every push to Github, that will make sure this API is still delivering what we expect.

This video gave me some good tips on this one being to keep your Contract tests outside of your Domain Logic. Secondly to focus on the KEYS and VALUES you care about.

KEYS

Focusing on the ones you care about can make this a ton easier. If I am calling an API and only want to know the ID and TITLE then I am going to make sure those exist and are in the same place every time.

Here are some results from the Marvel Comics API

{
    "offset": 0,
    "limit": 20,
    "total": 733,
    "count": 20,
    "results": [
        {
            "id": 55699,
            "digitalId": 0,
            "title": "Spider-Man (2016) #5",
            "issueNumber": 5,
            "variantDescription": "",
            "description": "BLACK CAT makes her move against SPIDER-MAN!!!",
            "modified": "2016-04-05T12:46:27-0400",
            "isbn": "",
            "upc": "75960608314500511",
            "diamondCode": "",
            "ean": "",

I just want to make sure "results" has a record, with ID and TITLE. So I can call this api via PHPUnit on a scheduled basis and make sure it is working if not ping us in Slack.

VALUES

Then there are values. Many times these change so I might not focus on the value of the value but the type. Integer, Array, Not-Null, Empty etc. What am I expecting?

PHPUnit

With these two things in place we can have a set of PHPUnit tests that can run on a schedule. You can set your phpunit.xml to hit these as separate Suites.

    <testsuites>
        <testsuite name="Application Test Suite">
            <directory>./tests/</directory>
        </testsuite>
        <testsuite name="Contracts Test Suite">
            <directory>./tests/contracts/</directory>
        </testsuite>
    </testsuites>

And just run those phpunit --testsuite Contracts Test Suite


Tags:

php testing