Practical PHP Testing Patterns: Transaction Rollback Teardown

DZone 's Guide to

Practical PHP Testing Patterns: Transaction Rollback Teardown

· Web Dev Zone ·
Free Resource

Maintaining isolation of tests when they have a database as Shared Fixture is not a trivial task. An important constraint is not having the headache of keeping track what manipulations on the database has your code done; in that case the rollback may not even be performed in case of a regression.

An alternative way to resetting the database via DELETE and TRUNCATE queries is to roll back a transaction which has been started in the setup phase during the teardown.


The phases of a database test involving Transaction Rollback Teardown are roughly the following:

  • begin transaction, usually in setUp().
  • arrange, act, assert actions in the various Test Methods.
  • rollback of the transaction in teardown(). The active transaction is never committed.

An issue with using this pattern is that code that already uses transaction is prone to generate errors, and ultimately should never be tested with this technique.

The rules for your safety are simple: the SUT should never start a transaction or committing it. Some databases support nested transaction levels, but it's very brittle to use them for testing purposes, and in case of any failure the whole suite will blow up as test executes teardowns at the wrong level of nesting.

This pattern safety is also difficult to ensure, as DDL statements like CREATE/DELETE or other commands may commit the current transaction automatically. Check the documentation of your testing database.

The advantage of this pattern is great performance: rollback is faster than every other command, including TRUNCATE. Moreover, if you encapsulate transactions well in your production code, most of it won't commit them (typically leaving the control over the transaction to an upper layer).

Doctrine 2

In a sense, we already use this pattern with an UnitOfWork ORM such as Doctrine 2 when we do not flush() the ORM in our code. The flow is:

  • The database is ready by setup.
  • Exercise code.
  • Check results as persisted or removed entities.
  • Instead of calling flush() over the Entity Manager, call clear().

In this case, the database never sees a transaction, as Doctrine 2 keeps everything in the Unit Of Work until you say to flush it.

Even when your code is calling flush(), you can explicitly use beginTransaction() and rollback() over the connection object: in this other scenario, the testing database sees an open transaction, but it's never committed and can be discarded in teardown() like the pattern prescribes.


The code sample is the same test case shown in the Table Truncation Teardown article, which now uses transactions to encapsulate the single tests. The various tests check the tables content is restored, along with the AUTOINCREMENT next value.

class TransactionRollbackTeardownTest extends PHPUnit_Framework_TestCase
    private static $sharedConnection;
    private $connection;

    public function setUp()
        if (self::$sharedConnection === null) {
            self::$sharedConnection = new PDO('sqlite::memory:');
            self::$sharedConnection->exec('CREATE TABLE users (
                name VARCHAR(255)
        $this->connection = self::$sharedConnection;

    public function teardown()

    public function testTableCanBePopulated()
        $this->connection->exec('INSERT INTO users (name) VALUES ("Giorgio")');
        $this->assertEquals(1, $this->howManyUsers());

    public function testTableRestartsFrom1()
        $this->assertEquals(0, $this->howManyUsers());
        $this->connection->exec('INSERT INTO users (name) VALUES ("Isaac")');
        $stmt = $this->connection->query('SELECT name FROM users WHERE id=1');
        $result = $stmt->fetch();
        $this->assertEquals('Isaac', $result['name']);

    public function testTableIsEmpty()
        $this->assertEquals(0, $this->howManyUsers());

    private function howManyUsers()
        $stmt = $this->connection->query('SELECT COUNT(*) AS number FROM users');
        $result = $stmt->fetch();
        return $result['number'];

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}