Приглашаем посетить
Толстой А.К. (tolstoy-a-k.lit-info.ru)

Section 6-3.  Suite-Level Setup

Previous
Table of Contents
Next

6-3. 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 tests reduces the value of the tests. The underlying design problem is that objects are too closely bound together. You will achieve better results by solving the underlying design problem and then writing tests using stubs (see the section "Stubs," later in this book), than by creating dependencies between tests at runtime and ignoring the opportunity to improve your design.


Previous
Table of Contents
Next