Suite-Level Setup

PHPUnit does not provide convenient support for suite-level setup. There aren't many good reasons to share fixtures between tests, but, in most cases, the need to do so stems from an unresolved design problem.

A good example of a fixture that makes sense to share across several tests is a database connection: you log into the database once and reuse the database connection instead of creating a new connection for each test. This makes your tests run faster. To do this, write your database tests in a test-case class named DatabaseTests, and wrap the test suite in a TestSetup decorator object that overrides setUp( ) to open the database connection and tearDown( ) to close the connection, as shown in Example 6. You can run the tests from DatabaseTests through the DatabaseTestSetup decorator by invoking, for instance, PHPUnit's command-line test runner with phpunit DatabaseTestSetup.

Example 6. Writing a suite-level setup decorator

<?php
require_once 'PHPUnit2/Framework/TestSuite.php';
require_once 'PHPUnit2/Extensions/TestSetup.php';

class DatabaseTestSetup extends PHPUnit2_Extensions_TestSetup 
{
  protected $connection = NULL;

  protected function setUp( ) {
    $this->connection = new PDO(
     'mysql:host=wopr;dbname=test',
		 'root',
		 ''
    );
  }

  protected function tearDown( ) {
    $this->connection = NULL;
  }

  public static function suite( ) {
    return new DatabaseTestSetup(
     new PHPUnit2_Framework_TestSuite('DatabaseTests')
    );
  }
}
?>

It cannot be emphasized enough that sharing fixtures between ...

Get PHPUnit Pocket Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.