Last active
August 29, 2015 14:11
-
-
Save trilopin/4acbdca95c9e2af4c39c to your computer and use it in GitHub Desktop.
unit test with phpunit mocking for phinx mysqladapter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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')); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
in the first version i wrote, expected_sql was in wrong order, now fixed