PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

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

Note: This article was originally published at Planet PHP on 17 January 2012.
Planet PHP

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:

"1.0" encoding="UTF-8"? A "false" backupStaticAttributes="false" colors="true" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" processIsolation="false" stopOnFailure="false" syntaxCheck="false" bootstrap="vendor/.composer/autoload.php" "Test Suite" ./testsA

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:

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

We are now ready to write our first test:

A // example.com/tests/Simplex/Tests/FrameworkTest.php A namespace Simplex\Tests; A use Simplex\Framework; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Exception\ResourceNotFoundException; A class FrameworkTest extends \PHPUnit_Framework_TestCase { public function testNotFoundHandling() { $framework = $this-getFrameworkForException(new ResourceNotFoundException()); A $response = $framework-handle(new Request()); A $this-assertEqual

Truncated by Planet PHP, read more at the original (another 8958 bytes)