Introduction

This article is about creating a simple phpunit test in Symfony. The reason you would want to run phpunit tests, is to verify that code changes you made still work. For example, if you query a home page, you are going to “expect” certain things to be on that page and when you make development code changes, when you run your phpunit test, you should get the same results. In other words the tests should pass (unless you are expecting failures).

Symfony Documentation

Symfony has fairly good documentation on how to get started writing phpunit tests on their Testing page. This is a good place to start reading to get familiar with the Goutte crawler and some basic testing.

A Simple Test

The following is some sample code that I used to run a simple phpunit test:

<?php
namespace Tests\AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DefaultControllerTest extends WebTestCase{
    public function testIndex(){
       $client = static::createClient(); // Create client.
       $crawler = $client->request('GET', '/'); // Get default content.

      // The HTML response code is 200.
      $this->assertEquals(200, $client->getResponse()->getStatusCode());

      // Asserts contains the specified text.
      $this->assertContains(
              'Application System',
              $client->getResponse()->getContent()
      );

      // Assert that there are exactly 1 h2 tags on the page
      $this->assertCount(1, $crawler->filter('h1'));

      // Asserts there are greater than 2 "<a>" tags - will fail.
      $this->assertGreaterThan(
          2,
          $crawler->filter('a')->count()
      );
   }
}

The above code simply gets the path “/”, which is the main page, then asserts the following:

  1. HTML response code is “200”.
  2. The page contains the text “Application System”.
  3. There is an exact count of 1 “h1” HTML tag.
  4. There are greater than 2 “a” HTML link tags.

For item 4, I am expecting that to fail, because I know that in my case I have exactly 2 “a” link tags on the page.

Running the Tests

To run the phpunit tests, from the Symfony project root folder run the following command:

phpunit

The tests will run and you should see a response similar to the following:

PHPunit_test

Notice the failure at step 4 as I expected. The PHPUnit version is also shown on the first output line.

This gives you an idea how to run simple phpunit tests in Symfony. Hopefully this helps you out.

Advertisements