Make Your phpUnit Tests Run Faster by Sharing Fixtures

There are few good reasons why you may want to share the fixtures between test, and most of the time the reason could be a bad design. For example, you would like to use share database connections, but your database adapter does not implement Singleton pattern.

In order to take advantage of sharing fixtures between tests within single Test Case, your test case should implement two public static methods setUpBeforeClass() and tearDownAfterClass(), and shared fixture itself should be protected static variable.

Following example shows sharing database fixture between tests:

<?php
class DatabaseTest extends PHPUnit_Framework_TestCase
{
    protected static $dbh;
 
    public static function setUpBeforeClass()
    {
        self::$dbh = new PDO('sqlite::memory:');
    }
 
    public static function tearDownAfterClass()
    {
        self::$dbh = NULL;
    }

    public function testShouldReturnCountGreaterThanZero()
    {
        $cmd = self::$dbh->prepare('SELECT * FROM users');
        $cmd->execute();
        $this->assertGreaterThanOrEqual(1, $cmd->rowCount());
    }
}

If you run multiple tests, the speed of the test will be greatly improved because database connections are shared between tests. Recommended would be fix the design problem and writing unit tests using stubs.


Comments

Popular posts from this blog

Stubbing and Mocking Static Methods with PHPUnit

Enable HTTP/2 Support in AWS ELB

How To Attach Your EBS volume to multiple EC2 instances