Last active
December 11, 2015 23:58
-
-
Save pablofmorales/4680373 to your computer and use it in GitHub Desktop.
When I try to mock a class which use QueryBuilder :(
This file contains 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 | |
class TestTest extends \PHPUnit_Framework_TestCase | |
{ | |
public function test_someAwfulTest() | |
{ | |
$expected = array(array('name' => 'buenos aires')); | |
$connectionMock = $this->getMockBuilder('Doctrine\DBAL\Connection') | |
->disableOriginalConstructor() | |
->getMock(); | |
$stmtMock = $this->getMockBuilder('Doctrine\DBAL\Driver\Mysqli\MysqliStatement') | |
->disableOriginalConstructor() | |
->getMock(); | |
$stmtMock->expects($this->once()) | |
->method('fetchAll') | |
->will($this->returnValue($expected)); | |
$queryMock = $this->getMockBuilder('Doctrine\DBAL\Query\QueryBuilder') | |
->disableOriginalConstructor() | |
->getMock(); | |
$queryMock->expects($this->once()) | |
->method('select') | |
->will($this->returnSelf()); | |
$queryMock->expects($this->once()) | |
->method('from') | |
->will($this->returnSelf()); | |
$queryMock->expects($this->once()) | |
->method('where') | |
->will($this->returnSelf()); | |
$queryMock->expects($this->once()) | |
->method('setParameter') | |
->will($this->returnSelf()); | |
$queryMock->expects($this->once()) | |
->method('execute') | |
->will($this->returnValue($stmtMock)); | |
$connectionMock->expects($this->once()) | |
->method('createQueryBuilder') | |
->will($this->returnValue($queryMock)); | |
$zones = new Models\ZonesMapper($connectionMock); | |
$this->assertEquals($expected, $zones->getChildren(13)); | |
} | |
} | |
?> | |
src/Models/ZonesMapper.php | |
<?php | |
namespace Models; | |
use Doctrine\DBAL\Connection; | |
class ZonesMapper | |
{ | |
private $_db; | |
public function __construct(Connection $db) | |
{ | |
$this->_db = $db; | |
} | |
public function getChildren($parentId) | |
{ | |
$queryBuilder = $this->_db->createQueryBuilder(); | |
$query = $queryBuilder->select("z.name", "z.seourl") | |
->from("loc_zones", "z") | |
->where("z.parent_id=?") | |
->setParameter(1, $parentId) | |
->execute(); | |
return $query->fetchAll(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Eso es feo, y lo sabes.