Buy

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():

28 lines src/AppBundle/Tests/Controller/Api/ProgrammerControllerTest.php
<?php
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:

28 lines src/AppBundle/Tests/Controller/Api/ProgrammerControllerTest.php
... 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():

33 lines src/AppBundle/Tests/Controller/Api/ProgrammerControllerTest.php
... 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.

33 lines src/AppBundle/Tests/Controller/Api/ProgrammerControllerTest.php
... lines 1 - 26
$this->assertEquals(201, $response->getStatusCode());
$this->assertTrue($response->hasHeader('Location'));
... 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:

33 lines src/AppBundle/Tests/Controller/Api/ProgrammerControllerTest.php
... lines 1 - 26
$this->assertEquals(201, $response->getStatusCode());
$this->assertTrue($response->hasHeader('Location'));
$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!

  • 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

    Cheers!

  • 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('https://api.github.com/', ['verify' => false]);, but better do not do this.

    Cheers!

  • 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