• Home
  • blog
  • Building a SparkPost Client: TDD with PhpUnit and Mockery

Building a SparkPost Client: TDD with PhpUnit and Mockery

In a previous post, we looked at SparkPost (as an alternative to Mandrill), and explored a bit of the official PHP client. The official client handles a decent amount of work, but I got to thinking about what it would take to build a new client.

The more I thought about it, the more it made sense. I could learn about the SparkPost API, and practice Test Driven Development at the same time. So, in this post we’ll look to do just that!

Home page screenshot

You can find the code for this post on Github.

Getting Started

To begin, we’re going to need Guzzle to make requests to the SparkPost API. We can install it with:

composer require guzzlehttp/guzzle

In addition, we’re going to be writing tests early, so we should also install PHPUnit and Mockery:

composer require --dev phpunit/phpunit mockery/mockery

Before we can run PHPUnit, we need to create a configuration file:

<?xml version="1.0" encoding="UTF-8"?>
            <directory suffix="Test.php">tests</directory>
        <whitelist addUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">src</directory>

This configuration file handles a number of things:

  1. Many of the root node attributes are sensible, intuitive defaults. The one I want to draw particular attention to is bootstrap: which tells PHPUnit to load Composer’s autoload code.
  2. We tell PHPUnit to load all files ending in Test.php, in the tests folder. It will treat all files with this suffix as though they are class files with a single class each. If it can’t instantiate any of the classes it finds (like abstract classes) then it will just ignore those.
  3. We tell PHPUnit to add all PHP files (from the src folder) to code coverage reporting. If you’re unsure what that is, don’t worry. We’ll look at it in a bit…

We can now run:


… and we should see:

New phpunit screen

Continue reading %Building a SparkPost Client: TDD with PhpUnit and Mockery%