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->assertEqual
Truncated by Planet PHP, read more at the original (another 8958 bytes)