Step 17: Testing

Testing

Fun fact: I found a bug while writing the tests in this chapter.

Symfony relies on PHPUnit for unit tests. Let’s install it:

is the first class we are going to write tests for. Generate a unit test:

  1. $ symfony console make:unit-test SpamCheckerTest

Testing the SpamChecker is a challenge as we certainly don’t want to hit the Akismet API. We are going to mock the API.

Let’s write a first test for when the API returns an error:

patch_file

  1. --- a/tests/SpamCheckerTest.php
  2. +++ b/tests/SpamCheckerTest.php
  3. @@ -2,12 +2,26 @@
  4. namespace App\Tests;
  5. +use App\Entity\Comment;
  6. +use App\SpamChecker;
  7. use PHPUnit\Framework\TestCase;
  8. +use Symfony\Component\HttpClient\MockHttpClient;
  9. +use Symfony\Component\HttpClient\Response\MockResponse;
  10. +use Symfony\Contracts\HttpClient\ResponseInterface;
  11. class SpamCheckerTest extends TestCase
  12. {
  13. - public function testSomething()
  14. + public function testSpamScoreWithInvalidRequest()
  15. {
  16. - $this->assertTrue(true);
  17. + $comment = new Comment();
  18. + $comment->setCreatedAtValue();
  19. + $context = [];
  20. +
  21. + $client = new MockHttpClient([new MockResponse('invalid', ['response_headers' => ['x-akismet-debug-help: Invalid key']])]);
  22. + $checker = new SpamChecker($client, 'abcde');
  23. +
  24. + $this->expectException(\RuntimeException::class);
  25. + $this->expectExceptionMessage('Unable to check for spam: invalid (Invalid key).');
  26. + $checker->getSpamScore($comment, $context);
  27. }
  28. }

The MockHttpClient class makes it possible to mock any HTTP server. It takes an array of MockResponse instances that contain the expected body and Response headers.

Then, we call the getSpamScore() method and check that an exception is thrown via the expectException() method of PHPUnit.

Run the tests to check that they pass:

  1. $ symfony php bin/phpunit

Let’s add tests for the happy path:

patch_file

  1. --- a/tests/SpamCheckerTest.php
  2. +++ b/tests/SpamCheckerTest.php
  3. @@ -24,4 +24,32 @@ class SpamCheckerTest extends TestCase
  4. $this->expectExceptionMessage('Unable to check for spam: invalid (Invalid key).');
  5. $checker->getSpamScore($comment, $context);
  6. }
  7. +
  8. + /**
  9. + * @dataProvider getComments
  10. + */
  11. + public function testSpamScore(int $expectedScore, ResponseInterface $response, Comment $comment, array $context)
  12. + {
  13. + $client = new MockHttpClient([$response]);
  14. + $checker = new SpamChecker($client, 'abcde');
  15. +
  16. + $score = $checker->getSpamScore($comment, $context);
  17. + $this->assertSame($expectedScore, $score);
  18. + }
  19. +
  20. + public function getComments(): iterable
  21. + {
  22. + $comment = new Comment();
  23. + $comment->setCreatedAtValue();
  24. + $context = [];
  25. +
  26. + $response = new MockResponse('', ['response_headers' => ['x-akismet-pro-tip: discard']]);
  27. + yield 'blatant_spam' => [2, $response, $comment, $context];
  28. +
  29. + $response = new MockResponse('true');
  30. + yield 'spam' => [1, $response, $comment, $context];
  31. +
  32. + $response = new MockResponse('false');
  33. + yield 'ham' => [0, $response, $comment, $context];
  34. + }
  35. }

PHPUnit data providers allow us to reuse the same test logic for several test cases.

Writing Functional Tests for Controllers

Testing controllers is a bit different than testing a “regular” PHP class as we want to run them in the context of an HTTP request.

Create a functional test for the Conference controller:

tests/Controller/ConferenceControllerTest.php

  1. namespace App\Tests\Controller;
  2. use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
  3. class ConferenceControllerTest extends WebTestCase
  4. {
  5. public function testIndex()
  6. {
  7. $client = static::createClient();
  8. $client->request('GET', '/');
  9. $this->assertResponseIsSuccessful();
  10. $this->assertSelectorTextContains('h2', 'Give your feedback');
  11. }
  12. }

Using Symfony\Bundle\FrameworkBundle\Test\WebTestCase instead of PHPUnit\Framework\TestCase as a base class for our tests gives us a nice abstraction for functional tests.

The $client variable simulates a browser. Instead of making HTTP calls to the server though, it calls the Symfony application directly. This strategy has several benefits: it is much faster than having round-trips between the client and the server, but it also allows the tests to introspect the state of the services after each HTTP request.

This first test checks that the homepage returns a 200 HTTP response.

Assertions such as assertResponseIsSuccessful are added on top of PHPUnit to ease your work. There are many such assertions defined by Symfony.

Tip

We have used / for the URL instead of generating it via the router. This is done on purpose as testing end-user URLs is part of what we want to test. If you change the route path, tests will break as a nice reminder that you should probably redirect the old URL to the new one to be nice with search engines and websites that link back to your website.

Note

We could have generated the test via the maker bundle:

  1. $ symfony console make:functional-test Controller\\ConferenceController

Configuring the Test Environment

By default, PHPUnit tests are run in the test Symfony environment as defined in the PHPUnit configuration file:

phpunit.xml.dist

  1. <phpunit>
  2. <php>
  3. <ini name="error_reporting" value="-1" />
  4. <server name="APP_ENV" value="test" force="true" />
  5. <server name="SHELL_VERBOSITY" value="-1" />
  6. <server name="SYMFONY_PHPUNIT_REMOVE" value="" />
  7. <server name="SYMFONY_PHPUNIT_VERSION" value="8.5" />
  8. </php>
  9. </phpunit>

    Note

    As seen in a previous chapter, APP_ENV=test means that the APP_ENV environment variable is set for the context of the command. On Windows, use --env=test instead: symfony console secrets:set AKISMET_KEY --env=test

    Working with a Test Database

    As we have already seen, the Symfony CLI automatically exposes the DATABASE_URL environment variable. When APP_ENV is test, like set when running PHPUnit, it changes the database name from main to main_test so that tests have their very own database. This is very important as we will need some stable data to run our tests and we certainly don’t want to override what we stored in the development database.

    Before being able to run the test, we need to “initialize” the test database (create the database and migrate it):

    1. $ APP_ENV=test symfony console doctrine:database:create
    2. $ APP_ENV=test symfony console doctrine:migrations:migrate -n

    If you now run the tests, PHPUnit won’t interact with your development database anymore. To only run the new tests, pass the path to their class path:

    Note that we are setting APP_ENV explicitely even when runing PHPUnit to let the Symfony CLI set the database name to main_test.

    Tip

    When a test fails, it might be useful to introspect the Response object. Access it via $client->getResponse() and it to see what it looks like.

    To be able to test the comment list, the pagination, and the form submission, we need to populate the database with some data. And we want the data to be the same between test runs to make the tests pass. Fixtures are exactly what we need.

    Install the Doctrine Fixtures bundle:

    1. $ symfony composer req orm-fixtures --dev

    A new src/DataFixtures/ directory has been created during the installation with a sample class, ready to be customized. Add two conferences and one comment for now:

    patch_file

    1. --- a/src/DataFixtures/AppFixtures.php
    2. +++ b/src/DataFixtures/AppFixtures.php
    3. @@ -2,6 +2,8 @@
    4. namespace App\DataFixtures;
    5. +use App\Entity\Comment;
    6. +use App\Entity\Conference;
    7. use Doctrine\Bundle\FixturesBundle\Fixture;
    8. use Doctrine\Persistence\ObjectManager;
    9. @@ -9,8 +11,24 @@ class AppFixtures extends Fixture
    10. {
    11. public function load(ObjectManager $manager)
    12. {
    13. - // $product = new Product();
    14. - // $manager->persist($product);
    15. + $amsterdam = new Conference();
    16. + $amsterdam->setCity('Amsterdam');
    17. + $amsterdam->setYear('2019');
    18. + $amsterdam->setIsInternational(true);
    19. + $manager->persist($amsterdam);
    20. +
    21. + $paris = new Conference();
    22. + $paris->setCity('Paris');
    23. + $paris->setYear('2020');
    24. + $paris->setIsInternational(false);
    25. + $manager->persist($paris);
    26. +
    27. + $comment1 = new Comment();
    28. + $comment1->setConference($amsterdam);
    29. + $comment1->setAuthor('Fabien');
    30. + $comment1->setEmail('[email protected]');
    31. + $comment1->setText('This was a great conference.');
    32. + $manager->persist($comment1);
    33. $manager->flush();
    34. }

    When we will load the fixtures, all data will be removed; including the admin user. To avoid that, let’s add the admin user in the fixtures:

    1. --- a/src/DataFixtures/AppFixtures.php
    2. +++ b/src/DataFixtures/AppFixtures.php
    3. @@ -2,13 +2,22 @@
    4. namespace App\DataFixtures;
    5. +use App\Entity\Admin;
    6. use App\Entity\Comment;
    7. use App\Entity\Conference;
    8. use Doctrine\Bundle\FixturesBundle\Fixture;
    9. use Doctrine\Persistence\ObjectManager;
    10. +use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
    11. class AppFixtures extends Fixture
    12. {
    13. + private $encoderFactory;
    14. +
    15. + public function __construct(EncoderFactoryInterface $encoderFactory)
    16. + {
    17. + $this->encoderFactory = $encoderFactory;
    18. + }
    19. +
    20. public function load(ObjectManager $manager)
    21. {
    22. $amsterdam = new Conference();
    23. @@ -30,6 +39,12 @@ class AppFixtures extends Fixture
    24. $comment1->setText('This was a great conference.');
    25. $manager->persist($comment1);
    26. + $admin = new Admin();
    27. + $admin->setRoles(['ROLE_ADMIN']);
    28. + $admin->setUsername('admin');
    29. + $admin->setPassword($this->encoderFactory->getEncoder(Admin::class)->encodePassword('admin', null));
    30. + $manager->persist($admin);
    31. +
    32. $manager->flush();
    33. }
    34. }

    Tip

    If you don’t remember which service you need to use for a given task, use the debug:autowiring with some keyword:

    1. $ symfony console debug:autowiring encoder

    Loading Fixtures

    Load the fixtures for the test environment/database:

    1. $ APP_ENV=test symfony console doctrine:fixtures:load

    Crawling a Website in Functional Tests

    As we have seen, the HTTP client used in the tests simulates a browser, so we can navigate through the website as if we were using a headless browser.

    Add a new test that clicks on a conference page from the homepage:

    patch_file

    1. --- a/tests/Controller/ConferenceControllerTest.php
    2. +++ b/tests/Controller/ConferenceControllerTest.php
    3. @@ -14,4 +14,19 @@ class ConferenceControllerTest extends WebTestCase
    4. $this->assertResponseIsSuccessful();
    5. $this->assertSelectorTextContains('h2', 'Give your feedback');
    6. }
    7. +
    8. + public function testConferencePage()
    9. + {
    10. + $client = static::createClient();
    11. + $crawler = $client->request('GET', '/');
    12. +
    13. + $this->assertCount(2, $crawler->filter('h4'));
    14. +
    15. + $client->clickLink('View');
    16. +
    17. + $this->assertPageTitleContains('Amsterdam');
    18. + $this->assertResponseIsSuccessful();
    19. + $this->assertSelectorTextContains('h2', 'Amsterdam 2019');
    20. + $this->assertSelectorExists('div:contains("There are 1 comments")');
    21. + }
    22. }

    Let’s describe what happens in this test in plain English:

    • Like the first test, we go to the homepage;
    • The request() method returns a Crawler instance that helps find elements on the page (like links, forms, or anything you can reach with CSS selectors or XPath);
    • Thanks to a CSS selector, we assert that we have two conferences listed on the homepage;
    • We then click on the “View” link (as it cannot click on more than one link at a time, Symfony automatically chooses the first one it finds);
    • We assert the page title, the response, and the page <h2> to be sure we are on the right page (we could also have checked for the route that matches);
    • Finally, we assert that there is 1 comment on the page. div:contains() is not a valid CSS selector, but Symfony has some nice additions, borrowed from jQuery.

    Instead of clicking on text (i.e. View), we could have selected the link via a CSS selector as well:

    1. $client->click($crawler->filter('h4 + p a')->link());

    Check that the new test is green:

    1. $ APP_ENV=test symfony php bin/phpunit tests/Controller/ConferenceControllerTest.php

    Submitting a Form in a Functional Test

    Do you want to get to the next level? Try adding a new comment with a photo on a conference from a test by simulating a form submission. That seems ambitious, doesn’t it? Look at the needed code: not more complex than what we already wrote:

    patch_file

    1. --- a/tests/Controller/ConferenceControllerTest.php
    2. +++ b/tests/Controller/ConferenceControllerTest.php
    3. @@ -29,4 +29,19 @@ class ConferenceControllerTest extends WebTestCase
    4. $this->assertSelectorTextContains('h2', 'Amsterdam 2019');
    5. $this->assertSelectorExists('div:contains("There are 1 comments")');
    6. }
    7. +
    8. + public function testCommentSubmission()
    9. + {
    10. + $client = static::createClient();
    11. + $client->submitForm('Submit', [
    12. + 'comment_form[author]' => 'Fabien',
    13. + 'comment_form[text]' => 'Some feedback from an automated functional test',
    14. + 'comment_form[email]' => '[email protected]',
    15. + 'comment_form[photo]' => dirname(__DIR__, 2).'/public/images/under-construction.gif',
    16. + ]);
    17. + $this->assertResponseRedirects();
    18. + $client->followRedirect();
    19. + $this->assertSelectorExists('div:contains("There are 2 comments")');
    20. + }
    21. }

    To submit a form via submitForm(), find the input names thanks to the browser DevTools or via the Symfony Profiler Form panel. Note the clever re-use of the under construction image!

    If you want to check the result in a browser, stop the Web server and re-run it for the test environment:

    1. $ symfony server:stop
    2. $ APP_ENV=test symfony server:start -d

    If you run the tests a second time, they should fail. As there are now more comments in the database, the assertion that checks the number of comments is broken. We need to reset the state of the database between each run by reloading the fixtures before each run:

    1. $ APP_ENV=test symfony console doctrine:fixtures:load
    2. $ APP_ENV=test symfony php bin/phpunit tests/Controller/ConferenceControllerTest.php

    Automating your Workflow with a Makefile

    Having to remember a sequence of commands to run the tests is annoying. This should at least be documented. But documentation should be a last resort. Instead, what about automating day to day activities? That would serve as documentation, help discovery by other developers, and make developer lives easier and fast.

    Using a Makefile is one way to automate commands:

    Makefile

    1. SHELL := /bin/bash
    2. tests: export APP_ENV=test
    3. tests:
    4. symfony console doctrine:database:drop --force || true
    5. symfony console doctrine:database:create
    6. symfony console doctrine:migrations:migrate -n
    7. symfony console doctrine:fixtures:load -n
    8. symfony php bin/phpunit [email protected]
    9. .PHONY: tests

    Warning

    In a Makefile rule, indentation must consist of a single tab character instead of spaces.

    Note the -n flag on the Doctrine command; it is a global flag on Symfony commands that makes them non interactive.

    Whenever you want to run the tests, use make tests:

    1. $ make tests

    Resetting the Database after each Test

    Resetting the database after each test run is nice, but having truly independent tests is even better. We don’t want one test to rely on the results of the previous ones. Changing the order of the tests should not change the outcome. As we’re going to figure out now, this is not the case for the moment.

    Move the testConferencePage test after the testCommentSubmission one:

    patch_file

    1. --- a/tests/Controller/ConferenceControllerTest.php
    2. +++ b/tests/Controller/ConferenceControllerTest.php
    3. @@ -15,21 +15,6 @@ class ConferenceControllerTest extends WebTestCase
    4. $this->assertSelectorTextContains('h2', 'Give your feedback');
    5. }
    6. - public function testConferencePage()
    7. - {
    8. - $client = static::createClient();
    9. - $crawler = $client->request('GET', '/');
    10. -
    11. - $this->assertCount(2, $crawler->filter('h4'));
    12. -
    13. - $client->clickLink('View');
    14. -
    15. - $this->assertPageTitleContains('Amsterdam');
    16. - $this->assertResponseIsSuccessful();
    17. - $this->assertSelectorTextContains('h2', 'Amsterdam 2019');
    18. - $this->assertSelectorExists('div:contains("There are 1 comments")');
    19. - }
    20. -
    21. public function testCommentSubmission()
    22. {
    23. $client = static::createClient();
    24. @@ -44,4 +29,19 @@ class ConferenceControllerTest extends WebTestCase
    25. $client->followRedirect();
    26. $this->assertSelectorExists('div:contains("There are 2 comments")');
    27. }
    28. +
    29. + public function testConferencePage()
    30. + {
    31. + $client = static::createClient();
    32. + $crawler = $client->request('GET', '/');
    33. +
    34. + $this->assertCount(2, $crawler->filter('h4'));
    35. +
    36. + $client->clickLink('View');
    37. +
    38. + $this->assertPageTitleContains('Amsterdam');
    39. + $this->assertResponseIsSuccessful();
    40. + $this->assertSelectorTextContains('h2', 'Amsterdam 2019');
    41. + $this->assertSelectorExists('div:contains("There are 1 comments")');
    42. + }
    43. }

    Tests now fail.

    To reset the database between tests, install DoctrineTestBundle:

    1. $ symfony composer req "dama/doctrine-test-bundle:^6" --dev

    You will need to confirm the execution of the recipe (as it is not an “officially” supported bundle):

    1. Symfony operations: 1 recipe (d7f110145ba9f62430d1ad64d57ab069)
    2. - WARNING dama/doctrine-test-bundle (>=4.0): From github.com/symfony/recipes-contrib:master
    3. The recipe for this package comes from the "contrib" repository, which is open to community contributions.
    4. Review the recipe at https://github.com/symfony/recipes-contrib/tree/master/dama/doctrine-test-bundle/4.0
    5. Do you want to execute this recipe?
    6. [y] Yes
    7. [n] No
    8. [a] Yes for all packages, only for the current installation session
    9. [p] Yes permanently, never ask again for this project
    10. (defaults to n): p

    Enable the PHPUnit listener:

    patch_file

    1. --- a/phpunit.xml.dist
    2. +++ b/phpunit.xml.dist
    3. @@ -27,6 +27,10 @@
    4. </whitelist>
    5. </filter>
    6. + <extensions>
    7. + <extension class="DAMA\DoctrineTestBundle\PHPUnit\PHPUnitExtension" />
    8. + </extensions>
    9. +
    10. <listeners>
    11. <listener class="Symfony\Bridge\PhpUnit\SymfonyTestsListener" />
    12. </listeners>

    And done. Any changes done in tests are now automatically rolled-back at the end of each test.

    Tests should be green again:

    1. $ make tests

    Using a real Browser for Functional Tests

    Functional tests use a special browser that calls the Symfony layer directly. But you can also use a real browser and the real HTTP layer thanks to Symfony Panther:

    You can then write tests that use a real Google Chrome browser with the following changes:

    1. --- a/tests/Controller/ConferenceControllerTest.php
    2. +++ b/tests/Controller/ConferenceControllerTest.php
    3. @@ -2,13 +2,13 @@
    4. namespace App\Tests\Controller;
    5. -use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
    6. +use Symfony\Component\Panther\PantherTestCase;
    7. -class ConferenceControllerTest extends WebTestCase
    8. +class ConferenceControllerTest extends PantherTestCase
    9. {
    10. public function testIndex()
    11. {
    12. - $client = static::createClient();
    13. + $client = static::createPantherClient(['external_base_uri' => $_SERVER['SYMFONY_PROJECT_DEFAULT_ROUTE_URL']]);
    14. $client->request('GET', '/');

    The SYMFONY_PROJECT_DEFAULT_ROUTE_URL environment variable contains the URL of the local web server.

    Another way to run functional tests is to use the . In addition to what you can do with functional tests, it can also perform performance tests.

    Refer to the step about “Performance” to learn more.


    This work, including the code samples, is licensed under a Creative Commons BY-NC-SA 4.0 license.