Mocking PDO with phpunit
You don't have to mock PDO. Here example how it works:
ConnectionTest.php:
<?php
class ConnectionTest extends PHPUnit_Extensions_Database_TestCase
{
public function getConnection()
{
$database = 'myguestbook';
$user = 'root';
$password = '';
$pdo = new PDO('mysql:host=localhost;dbname=myguestbook', $user, $password);
$pdo->exec('CREATE TABLE IF NOT EXISTS guestbook (id int, content text, user text, created text)');
return $this->createDefaultDBConnection($pdo, $database);
}
public function getDataSet()
{
return $this->createFlatXMLDataSet(__DIR__.'/dataSets/myFlatXmlFixture.xml');
}
public function testGetRowCount()
{
$this->assertEquals(2, $this->getConnection()->getRowCount('guestbook'));
}
}
myFlatXmlFixture.xml
<?xml version="1.0" ?>
<dataset>
<guestbook id="1" content="Hello buddy!" user="joe" created="2010-04-24 17:15:23" />
<guestbook id="2" content="I like it!" user="nancy" created="2010-04-26 12:14:20" />
</dataset>
Result:
PHPUnit 4.7.6 by Sebastian Bergmann and contributors.
.
Time: 215 ms, Memory: 5.25Mb
OK (1 test, 1 assertion)
Main point in tests against db is don't mock db but also create absolutely same PDO connection not to production db but to db for test, it can be mysql, sqlite etc...
Have you tried viewing the documentation?
They seem to be using a traditional PDO
object using an in-memory sqlite connection by loading it with xml data like you are trying to do
<?php
class AdProvidersTest extends PHPUnit_Extensions_Database_TestCase
{
/**
* @return PHPUnit_Extensions_Database_DB_IDatabaseConnection
*/
public function getConnection()
{
$pdo = new PDO('sqlite::memory:');
return $this->createDefaultDBConnection($pdo, ':memory:');
}
}
Edit: May 2020 - Unit tests are to test units of code, not to test your data sets. It is best practice to Mock your dependencies to return known data sets, not to query in-memory databases. Querying data is best suited for integration tests, which are an entirely different set of tests. See https://phpunit.readthedocs.io/en/9.1/test-doubles.html?highlight=database#stubs