Create your own framework... on top of the Symfony2 Components (part 8)

Fabien Potencier

January 17, 2012

This article is part of a series of articles that explains how to create a framework with the Symfony2 Components: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12.

Some watchful readers pointed out some subtle but nonetheless important bugs in the framework we have built yesterday. When creating a framework, you must be sure that it behaves as advertised. If not, all the applications based on it will exhibit the same bugs. The good news is that whenever you fix a bug, you are fixing a bunch of applications too.

Today's mission is to write unit tests for the framework we have created by using PHPUnit. Create a PHPUnit configuration file in example.com/phpunit.xml.dist:

<?xml version="1.0" encoding="UTF-8"?>
 
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/.composer/autoload.php"
>
    <testsuites>
        <testsuite name="Test Suite">
            <directory>./tests</directory>
        </testsuite>
    </testsuites>
</phpunit>
 

This configuration defines sensible defaults for most PHPUnit settings; more interesting, the autoloader is used to bootstrap the tests, and tests will be stored under the example.com/tests/ directory.

Now, let's write a test for "not found" resources. To avoid the creation of all dependencies when writing tests and to really just unit-test what we want, we are going to use test doubles. Test doubles are easier to create when we rely on interfaces instead of concrete classes. Fortunately, Symfony2 provides such interfaces for core objects like the URL matcher and the controller resolver. Modify the framework to make use of them:

<?php
 
// example.com/src/Simplex/Framework.php
 
namespace Simplex;
 
// ...
 
use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
 
class Framework
{
    protected $matcher;
    protected $resolver;
 
    public function __construct(UrlMatcherInterface $matcher, ControllerResolverInterface $resolver)
    {
        $this->matcher = $matcher;
        $this->resolver = $resolver;
    }
 
    // ...
}
 

We are now ready to write our first test:

<?php
 
// example.com/tests/Simplex/Tests/FrameworkTest.php
 
namespace Simplex\Tests;
 
use Simplex\Framework;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
 
class FrameworkTest extends \PHPUnit_Framework_TestCase
{
    public function testNotFoundHandling()
    {
        $framework = $this->getFrameworkForException(new ResourceNotFoundException());
 
        $response = $framework->handle(new Request());
 
        $this->assertEquals(404, $response->getStatusCode());
    }
 
    protected function getFrameworkForException($exception)
    {
        $matcher = $this->getMock('Symfony\Component\Routing\Matcher\UrlMatcherInterface');
        $matcher
            ->expects($this->once())
            ->method('match')
            ->will($this->throwException($exception))
        ;
        $resolver = $this->getMock('Symfony\Component\HttpKernel\Controller\ControllerResolverInterface');
 
        return new Framework($matcher, $resolver);
    }
}
 

This test simulates a request that does not match any route. As such, the match() method returns a ResourceNotFoundException exception and we are testing that our framework converts this exception to a 404 response.

Executing this test is as simple as running phpunit from the example.com directory:

$ phpunit

I do not explain how the code works in details as this is not the goal of this series, but if you don't understand what the hell is going on, I highly recommend you to read PHPUnit documentation on test doubles.

After the test ran, you should see a green bar. If not, you have a bug either in the test or in the framework code!

Adding a unit test for any exception thrown in a controller is just as easy:

public function testErrorHandling()
{
    $framework = $this->getFrameworkForException(new \RuntimeException());
 
    $response = $framework->handle(new Request());
 
    $this->assertEquals(500, $response->getStatusCode());
}
 

Last, but not the least, let's write a test for when we actually have a proper Response:

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Controller\ControllerResolver;
 
public function testControllerResponse()
{
    $matcher = $this->getMock('Symfony\Component\Routing\Matcher\UrlMatcherInterface');
    $matcher
        ->expects($this->once())
        ->method('match')
        ->will($this->returnValue(array(
            '_route' => 'foo',
            'name' => 'Fabien',
            '_controller' => function ($name) {
                return new Response('Hello '.$name);
            }
        )))
    ;
    $resolver = new ControllerResolver();
 
    $framework = new Framework($matcher, $resolver);
 
    $response = $framework->handle(new Request());
 
    $this->assertEquals(200, $response->getStatusCode());
    $this->assertContains('Hello Fabien', $response->getContent());
}
 

In this test, we simulate a route that matches and returns a simple controller. We check that the response status is 200 and that its content is the one we have set in the controller.

To check that we have covered all possible use cases, run the PHPUnit test coverage feature (you need to enable XDebug first):

$ phpunit --coverage-html=cov/

Open example.com/cov/src_Simplex_Framework.php.html in a browser and check that all the lines for the Framework class are green (it means that they have been visited when the tests were executed).

Thanks to the simple object-oriented code that we have written so far, we have been able to write unit-tests to cover all possible use cases of our framework; test doubles ensured that we were actually testing our code and not Symfony2 code.

Now that we are confident (again) about the code we have written, we can safely think about the next batch of features we want to add to our framework.

Discussion

gravatar Christophe Coevoet  — January 17, 2012 10:58   #1
You could even simplify the phpunit config as most values are the PHPUnit defaults. The only you really need are the bootstrap and the colors attributes.
gravatar BenoĆ®t Merlet  — January 17, 2012 13:13   #2
I also don't quite understand why the PHPUnit config file has the ".dist" suffix in this case.
gravatar Jonathan Ingram  — January 17, 2012 14:12   #3
Someone correct me if I am wrong on anything.

You'll use the ".dist" file (stands for distribution) to be stored in your repository so that other developers can simply copy a default config. Then you'll use the standard XML file (without ".dist") if your development environment has some different settings to those used by most others (i.e. the one in the repo). You'll also want to ignore the standard XML file in your repository ignore file because that is specific to your development environment.
gravatar Jonathan Ingram  — January 17, 2012 14:12   #4
Someone correct me if I am wrong on anything.

You'll use the ".dist" file (stands for distribution) to be stored in your repository so that other developers can simply copy a default config. Then you'll use the standard XML file (without ".dist") if your development environment has some different settings to those used by most others (i.e. the one in the repo). You'll also want to ignore the standard XML file in your repository ignore file because that is specific to your development environment.
gravatar Christian Schaefer  — January 17, 2012 15:01   #5
@Jonathan you're completely right. I also summed it up in a bit more detail on my blog: http://www.testically.org/2010/08/24/best-practice-how-to-ship-phpunit-configuration/
gravatar Volker Dusch  — January 17, 2012 18:03   #6
A simple use case for this .dist file is that one of your developers is one windows and wants to turn of the colors as they don't work on windows without installing various dlls. (PHPUnit might auto detect that in the future but just as an example.)

He then could have a "phpunit.xml" that with just:

<phpunit colors="false" />

or maybe someone always want to see the code coverage on the command line

<phpunit>
<loggers>
<log type="coverage-text" target="php://stdout" />
</loggers>
</phpunit>

without repeating the whole config file.
gravatar Arnaud Kleinpeter  — January 18, 2012 18:48   #7
I'm handling several problems with PHPUnit installation, on Ubuntu 11.10. Maybe someone has a link showing a clean a simple way to install it?
gravatar Thanos Polymeneas  — February 01, 2012 09:22   #8
In general shouldn't everything apart from the Framework class be a mock in the FrameworkTest? Is it for simplification of this specific case or is something else considered better practice?
gravatar Isidro Merayo Castellano  — February 16, 2012 14:00   #9
Hi,
I have problems with Mock, because in the __construct() must be an instance of Symfony\Component\Routing\Matcher\UrlMatcher, instance of Mock_UrlMatcherInterface_58542ade :)

My enviroment: php 5.3.6 and PHPUnit 3.6.10

A nice Mock Framework named Phake http://phake.digitalsandwich.com/docs/html/preface.html :)
gravatar Nikola Nikolic  — March 04, 2012 20:56   #10
@Thanos Polymeneas : This worked for 11.04, don't know if it will work for 11.10, but I suppose it should.

http://www.giocc.com/installing-phpunit-on-ubuntu-11-04-natty-narwhal.html