Introduction

For a TRIO project I’m working on for Taft College, I needed to run some PHPUnit Functional tests for the TRIO Forms system I’m developing. Testing in Symfony is well documented. In this article, I will show is simple Functional test example.

Running Tests with PHPUnit Phar

If you try to run phpunit directly from a phar in your Symfony project, you most likely will get the following error:

PHP Fatal error:  Undefined class constant 'PARSE_CONSTANT' in
vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/
Loader/YamlFileLoader.php on line 396

This error occurs from a PHPUnit namespace issue and is described in more detail in the following article.

The workaround is to instead use Symfony’s vendor binaries, which will be described further down in this article.

Sample code

I created the following simple code will will crawl my application’s homepage, check for a certain string on the page, and also look for the text of a link on the page:

<?php
// tests/AppBundle/Functional/DefaultControllerTest.php
namespace tests\AppBundle\Functional;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DefaultControllerTest extends WebTestCase
{
   public function testShowHomepage()
   {
      $client = static::createClient( array(), array(
         'HTTP_HOST' => 'trio2', // Set HOST HTTP Header.
         'HTTP_USER_AGENT' => 'Symfony Browser/1.0', // Set Agent header.
      ));

      $crawler = $client->request('GET', '/'); // Gets crawler for homepage.
      $appLink = $crawler->selectLink('TRIO Application'); // Check for link.
      var_dump( $appLink->text() ); // Dump the link text for debugging.

      // Make sure this text appears on the page.
      $this->assertGreaterThan(
         0,
         $crawler->filter('html:contains("TRIO-SSS Application & Eligibility")')->count()
      );

      // Verify that the link text is "TRIO Application".
      $this->assertcontains(
         'TRIO Application',
         $appLink->text() // Get link text from crawler object.
      );
   }
}

NoticeĀ on Line 18, I do a var_dump() of the crawler text, this is just a debugging line so that I can see the text is what I’m trying to assert later.

Running the Test

Instead of running PHPUnit from a phar, we can run from Symfony’s binaries like so:

./vendor/bin/phpunit tests/AppBundle/Functional/DefaultControllerTest.php

Where “./vendor/bin/phpunit” is the path to the phpunit binary. And in this case I’ve specified to run just the one test case by specifying the folder path and filename with “tests/AppBundle/Functional/DefaultControllerTest.php”.

The output will look like the following screenshot:

phpunit_1strun

There are a number of options you can specify when running phpunit. To see what these options are, just use this command:

./vendor/bin/phpunit --help

Hope this helps you out!

Advertisements