Eric Hogue on February 12th, 2013

The subject of mocking a PDO object in PHPUnit has come around a few times lately. It cannot be done like normal classes because a PDO object cannot be serialized.

$pdo = $this->getMockBuilder('PDO')
    ->disableOriginalConstructor()
    ->getMock();

This will work on another class, but with PDO you will get this error:

PDOException: You cannot serialize or unserialize PDO instances

The solution

My solution for this problem is to create a class that derive from PDO. This class has only an empty constructor. Then you can mock this class, making sure that you don’t disable the original constructor. This way the mocked object can be passed to the code to test even if this code does type hinting.

class PDOMock extends \PDO {
    public function __construct() {}
}

class PDOTest extends \PHPUnit_Framework_TestCase {
    public function setup() {
        $pdo = $this->getMockBuilder('PDOMock')
            ->getMock();
    }
}

Tags: , ,

3 Comments on Mocking PDO in PHPUnit

  1. Nice and easy! And there are no weird side-effects to doing this? I mean, are there no real reasons that PDO complains about serialization? Or does the subclassing actually make it serializable?

  2. Eric Hogue says:

    I had the same worries when I start doing this. I have been doing it for a few months now and I never had any issues.

    I think that since it’s not creating a database connection the serialization is not an issue anymore.

  3. yitznewton says:

    Yup, I arrived at the same solution. Thanks for sharing!

Leave a Reply