DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Data Engineering
  3. Databases
  4. Practical PHP Testing Patterns: Transaction Rollback Teardown

Practical PHP Testing Patterns: Transaction Rollback Teardown

Giorgio Sironi user avatar by
Giorgio Sironi
·
May. 11, 11 · Interview
Like (0)
Save
Tweet
Share
5.80K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Implementation

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.

Example

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.

<?php
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 (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name VARCHAR(255)
            )');
        }
        $this->connection = self::$sharedConnection;
        $this->connection->beginTransaction();
    }

    public function teardown()
    {
        $this->connection->rollback();
    }

    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'];
    }
}
PHP Rollback (data management) Database

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • 11 Observability Tools You Should Know
  • Spring Boot vs Eclipse Micro Profile: Resident Set Size (RSS) and Time to First Request (TFR) Comparative
  • Unlocking the Power of Elasticsearch: A Comprehensive Guide to Complex Search Use Cases
  • The 5 Books You Absolutely Must Read as an Engineering Manager

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: