Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine
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

With a Subscription, click any sentence in the script to jump to that part of the video!

Login Subscribe

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

<?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:

... 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());
$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:

... 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!

8
Login or Register to join the conversation
Default user avatar
Default user avatar Miguel Angel Carvajal Rivero | posted 5 years ago

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

1 Reply

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!

Reply
Default user avatar
Default user avatar Александр | Victor | posted 4 years ago

base_uri, not base_url

Reply

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".

Cheers!

Reply
Shaun T. Avatar
Shaun T. Avatar Shaun T. | posted 5 years ago

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?

Reply

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: http://symfony.com/doc/curr... . You need to authenticate user, create a new post and then check that the post has the current user in createdBy field.

Cheers!

Reply
Default user avatar
Default user avatar Mike Milano | posted 5 years ago

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.

Reply

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!

Reply
Cat in space

"Houston: no signs of life"
Start the conversation!

This tutorial uses an older version of Symfony. The concepts of REST are still valid, but I recommend using API Platform in new Symfony apps.

What PHP libraries does this tutorial use?

// composer.json
{
    "require": {
        "php": ">=5.3.3",
        "symfony/symfony": "2.6.*", // v2.6.11
        "doctrine/orm": "~2.2,>=2.2.3,<2.5", // v2.4.7
        "doctrine/dbal": "<2.5", // v2.4.4
        "doctrine/doctrine-bundle": "~1.2", // v1.4.0
        "twig/extensions": "~1.0", // v1.2.0
        "symfony/assetic-bundle": "~2.3", // v2.6.1
        "symfony/swiftmailer-bundle": "~2.3", // v2.3.8
        "symfony/monolog-bundle": "~2.4", // v2.7.1
        "sensio/distribution-bundle": "~3.0,>=3.0.12", // v3.0.21
        "sensio/framework-extra-bundle": "~3.0,>=3.0.2", // v3.0.7
        "incenteev/composer-parameter-handler": "~2.0", // v2.1.0
        "hautelook/alice-bundle": "0.2.*", // 0.2
        "jms/serializer-bundle": "0.13.*" // 0.13.0
    },
    "require-dev": {
        "sensio/generator-bundle": "~2.3", // v2.5.3
        "behat/behat": "~3.0", // v3.0.15
        "behat/mink-extension": "~2.0.1", // v2.0.1
        "behat/mink-goutte-driver": "~1.1.0", // v1.1.0
        "behat/mink-selenium2-driver": "~1.2.0", // v1.2.0
        "phpunit/phpunit": "~4.6.0" // 4.6.4
    }
}
userVoice