This tutorial has a new version, check it out!

Add a Test!

Keep on Learning!

If you liked what you've learned so far, dive in!
Subscribe to get access to this tutorial plus
video, code and script downloads.

Start your All-Access Pass
Buy just this tutorial for $10.00

This testing.php file is basically already a test... except it's missing the most important part: the ability to start shouting when something breaks.

To test our API, we'll use PHPUnit! Yes! Awesome! I'm excited because even though PHPUnit isn't the most exciting tool, it's solid - and we're going to do some cool stuff with our tests.

TIP In our other REST tutorial, we tested with Behat. Both are great, and really the same under the surface.

Create that Test

Create a Tests directory inside AppBundle. Now mimic your directory structure. So, add a Controller directory, then an API directory, and finish it with a new PHPUnit test class for ProgrammerController. Be a good programmer and fill in the right namespace. All these directories: technically unnecessary. But now we've got a sane setup.

Of course, we'll test our POST endpoint - so create public function testPOST():

namespace AppBundle\Tests\Controller\Api;
class ProgrammerControllerTest extends \PHPUnit_Framework_TestCase
public function testPOST()
... lines 8 - 25

I'm being inconsistent - the controller is newAction, but this method is testPOST - it would be cool to have these match - maybe even with a mixture of the two - like postNewAction().

Anyways, let's go steal our first request code from testing.php and paste it into testPOST:

... lines 1 - 5
public function testPOST()
$client = new \GuzzleHttp\Client([
'base_url' => 'http://localhost:8000',
'defaults' => [
'exceptions' => false
$nickname = 'ObjectOrienter'.rand(0, 999);
$data = array(
'nickname' => $nickname,
'avatarNumber' => 5,
'tagLine' => 'a test dev!'
// 1) Create a programmer resource
$response = $client->post('/api/programmers', [
'body' => json_encode($data)
... lines 27 - 28

Ok cool. No asserts yet - but let's see if it blows up. I already installed PHPUnit into this project, so run php bin/phpunit -c app then the path to the test:

php bin/phpunit -c app src/AppBundle/Tests/Controller/Api/ProgrammerControllerTest.php

Pretty green! No assertions yet, but also no explosions. Solid start team!

Be Assertive

Ok, what should we assert? Always start with the status code - $this->assertEquals() that the expected 201 equals $response->getStatusCode():

... lines 1 - 21
// 1) Create a programmer resource
$response = $client->post('/api/programmers', [
'body' => json_encode($data)
$this->assertEquals(201, $response->getStatusCode());
... lines 28 - 33

Second: what response header should we send back whenever we create a resource? Location! Right now, just assertTrue that $response->hasHeader('Location'). Soon, we'll assert the actual value.

... lines 1 - 26
$this->assertEquals(201, $response->getStatusCode());
... lines 29 - 33

And to put a bow on things, let's json_decode the response body into an array, and just assert that is has a nickname key with assertArrayHasKey, with nickname and $data:

... lines 1 - 26
$this->assertEquals(201, $response->getStatusCode());
$finishedData = json_decode($response->getBody(true), true);
$this->assertArrayHasKey('nickname', $finishedData);
... lines 31 - 33

In a second, we'll assert the actual value. It's not a super-tight test yet, but let's give it a shot:

php bin/phpunit -c app src/AppBundle/Tests/Controller/Api/ProgrammerControllerTest.php

Yes! This time we deserve that green.

Leave a comment!

  • 2019-04-12 Victor Bocharsky

    Hey Alexandr,

    Thank you for this tip! Yeah, in a newer version of Guzzle (newer than we use in this course) they renamed "base_url" -> "base_uri".


  • 2019-04-12 Александр

    base_uri, not base_url

  • 2018-06-04 Victor Bocharsky

    Hey Shaun,

    You probably need an integration test, but it depends on tools you use. I suppose you use PHPUnit, so take a look at functional tests: . You need to authenticate user, create a new post and then check that the post has the current user in createdBy field.


  • 2018-06-03 Shaun

    In my app I am using Doctrine Blameable Extension, so it sets the current user when creating a post on the createdBy field.

    How can I handle this when running my tests?

  • 2017-09-18 Diego Aguiar

    Hey Mike Milano

    You are absolutely right, Guzzle has changed a bit since the tutorial was recorded. Thanks for informing us, we will add a note to the video to prevent other users from this "What a heck" moment


  • 2017-09-18 Mike Milano

    I was getting the error: "Failed to connect to localhost port 80:", even though I was specifying `http://localhost:8000`.

    I resolved this by changing `base_url` to `base_uri` in the config of the GuzzleHttp Client constructor.

    Also, echoing the response was not working. I had to `echo $response->getBody();`

    I am running PHP 7.1 locally. Perhaps this or Guzzle changes since this video was produced are factors.

  • 2017-02-14 Victor Bocharsky

    Hey Miguel,

    I bet you have bad URL for your request. What's it? Is it something relative like '/'? Try to use absolute URL. Does it fix you problem?

    P.S. You can disable verification with: $response = $client->get('', ['verify' => false]);, but better do not do this.


  • 2017-02-14 Miguel Angel Carvajal Rivero

    I am getting the following error
    GuzzleHttp\Exception\RequestException : cURL error 3: <url> malformed when configuring the test