Skip to content

Instantly share code, notes, and snippets.

@pablofmorales
Last active December 11, 2015 23:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pablofmorales/4680373 to your computer and use it in GitHub Desktop.
Save pablofmorales/4680373 to your computer and use it in GitHub Desktop.
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
Copy link

exos commented Jan 31, 2013

Eso es feo, y lo sabes.

@pablofmorales
Copy link
Author

Decime porque @exos

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