Reputation: 1700
i am trying to test a class with two methods. both interact with a database which is the why im am trying to work with PDO mock object. I couldn't find much documentation about mocking PDO object and working with them but after following one tutorial that looked pretty close to what i need i ended up with a PDO mock object, but i don't understand how should i use it.
to make thing simple this is my class with the first method i want to test:
<?php
use Slim\Slim;
class AdProviders {
public $providers = null;
protected $db = null;
function __construct() {
}
function getDbh() {
if ($this->db === null){
$this->db = Slim::getInstance()->db;
}
return $this->db->getConnection();
}
}
and according to the db schema this is how i created the PDO object:
<?php
require dirname(__FILE__).'/../../src/vendor/autoload.php';
class AdProvidersTest extends PHPUnit_Framework_TestCase
{
public function dataProvider()
{
return array (
array (1, '1st', 'desc_1', 11),
array (2, '2nd', 'desc_2', 22),
array (3, '3rd', 'desc_3', 33),
);
}
/**
* @dataProvider dataProvider
*/
public function testAdProviders($id, $name, $desc, $account_id)
{
$data = array (
array (
'id' => $id,
'name' => $name,
'description' => $desc,
'account_id' => $account_id
)
);
$stmt = $this->getMock('PDOStatement', array ('fetchAll'));
$stmt->expects($this->any())
->method('fetchAll')
->will($this->returnValue($data));
$pdo = $this->getMock('PDO', array('prepare'),
array('sqlite:dbname=:memory'),'PDOMock_' . uniqid(),true);
$pdo->expects($this->any())
->method('prepare')
->will($this->returnValue($stmt));
}
}
Now i am really lost with how should i test the getDbh()
method ... is this the correct way to create a PDO mock for the purpose of my test?
and if so, how can i use it to test the method?
any kind of guidance will be highly appreciated... thx
Upvotes: 2
Views: 959
Reputation: 20286
You need to inject this mock into Slim::getInstance() that is why it is bad to use singletons and better to use dependency injection pattern.
It is kind a senseless to mock PDO where you can't change PDO in Slim::getInstance()->db
What you really may test here is whether method getDbh() returns instance of Connection.
Upvotes: 3