Skip to content

Instantly share code, notes, and snippets.

@pablofmorales pablofmorales/gist:4680373
Last active Dec 11, 2015

Embed
What would you like to do?
When I try to mock a class which use QueryBuilder :(
<?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();
}
}
@exos

This comment has been minimized.

Copy link

commented Jan 31, 2013

Eso es feo, y lo sabes.

@pablofmorales

This comment has been minimized.

Copy link
Owner Author

commented Jan 31, 2013

Decime porque @exos

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.