Skip to content

Instantly share code, notes, and snippets.

@trilopin
Last active August 29, 2015 14:11
Show Gist options
  • Save trilopin/4acbdca95c9e2af4c39c to your computer and use it in GitHub Desktop.
Save trilopin/4acbdca95c9e2af4c39c to your computer and use it in GitHub Desktop.
unit test with phpunit mocking for phinx mysqladapter
<?php
namespace Test\Phinx\Db\Adapter;
use Symfony\Component\Console\Output\NullOutput;
use Phinx\Db\Adapter\MysqlAdapter;
//trick for allow mocking PDO
class PDOMock extends \PDO
{
public function __construct() {}
}
//trick for allow mocking connection
class MysqlAdapterTester extends MysqlAdapter
{
public function setConnection($connection)
{
$this->connection = $connection;
}
}
class MysqlAdapterUnitTest extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
if (!TESTS_PHINX_DB_ADAPTER_MYSQL_ENABLED) {
$this->markTestSkipped('Mysql tests disabled. See TESTS_PHINX_DB_ADAPTER_MYSQL_ENABLED constant.');
}
$this->adapter = new MysqlAdapterTester([], new NullOutput());
$this->conn = $this->getMockBuilder('PDOMock')
->disableOriginalConstructor()
->setMethods( array( 'query', 'execute' ) )
->getMock();
$this->result = $this->getMockBuilder('stdclass')
->disableOriginalConstructor()
->setMethods( array( 'fetch' ) )
->getMock();
$this->adapter->setConnection($this->conn);
}
public function testHasDatabaseExists()
{
$this->result->expects($this->at(0))
->method('fetch')
->will($this->returnValue(array('SCHEMA_NAME' => 'database_name')));
$this->result->expects($this->at(1))
->method('fetch')
->will($this->returnValue(null));
$expected_sql = "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'database_name'";
$this->conn->expects($this->once())
->method('query')
->with($this->equalTo($expected_sql))
->will($this->returnValue($this->result));
$this->assertTrue($this->adapter->hasDatabase('database_name'));
}
public function testHasDatabaseNotExists()
{
$this->result->expects($this->once())
->method('fetch')
->will($this->returnValue(null));
$expected_sql = "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'database_name2'";
$this->conn->expects($this->once())
->method('query')
->with($this->equalTo($expected_sql))
->will($this->returnValue($this->result));
$this->assertFalse($this->adapter->hasDatabase('database_name2'));
}
}
@trilopin
Copy link
Author

in the first version i wrote, expected_sql was in wrong order, now fixed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment