recently I came across Mockery Framework for PHP mock object. I have a class which has constructor which takes postgreSQL connection parameters and connects to database and other methods for DML operations. I want to write test cases for these methods without actual connecting to database, hence want to use Mockery.
Below is a simple example of DBConnection class. Could any one please give me a sample code for running test case for select method?
class DBConnection {
private $conn; //db connection
private $debug = false;
private $schema;
public function __construct($host, $user, $pass, $db, $schema = 'main', $debug = DEBUG) {
$this->debug = $debug;
$this->conn = pg_connect("host=$host user=$user password=$pass dbname=$db");
if(!$this->conn) {
throw new DatabaseException('Database connection failed');
}
}
public function select() {
$result = pg_prepare($this->conn, "my_query", 'SELECT * FROM shops WHERE name = $1');
$result = pg_execute($this->conn, "my_query", array("Joe's Widgets"));
return $result;
}
}
I'm assuming you want to mock the DBConnection->select()
method and ensure that the pg_prepare()
and pg_execute()
functions are called.
If the above is true, I wrote a composer package to help try to test php function calls unit-testing/function-spy
(https://github.com/unit-testing/function-spy)
First, you'll have to namespace your DBConnection
class. Let's assume it's in namespace MyNamespace
. Then in your test, you can do something like this:
<?php namespace MyNamespace
use UnitTesting\FunctionSpy\Spy;
class DBConnectionTest extends \PHPUnit_Framework_TestCase {
use \UnitTesting\FunctionSpy\SpyTrait;
protected function setUp()
{
// init the spy
$this->initSpy();
}
protected function tearDown()
{
// flush the spy so we can reset the calls after every test
$this->flushSpy();
}
function test_construct_callsPgConnect_AndSetsConnection()
{
// create a fake return value for pg_connect()
$this->spy['pg_connect'] = 'connection';
$object = new DBConnection('host', 'user', 'pass', 'db', 'schema');
$this->assertFunctionLastCalledWith('pg_connect', array('host=host user=user password=pass dbname=db'));
$conn = $object->getConnection(); // your class doesn't have this method implemented, but it just returns the connection
$this->assertEquals('connection', $conn);
}
}
function pg_connect()
{
return Spy::pg_connect();
}