Getting a mock Doctrine\ORM\QueryBuilder Getting a mock Doctrine\ORM\QueryBuilder symfony symfony

Getting a mock Doctrine\ORM\QueryBuilder


I'm not sure how to do it with PHPUnit, but I would recommend checking out Mockery for your PHP mocking needs. It's a really powerful library which allows you to mock the EntityManager pretty easily, and therefore anything that it will return.

For your use case, you can easily create a Mock entity manager than will return you a mock query builder:

$mockEm = \Mockery::mock('\Doctrine\ORM\EntityManager');$mockQb = \Mockery::mock('\Doctrine\ORM\QueryBuilder');$mockEm->shouldReceive('createQueryBuilder')->andReturn($mockQb);

Then you can use Mockery's core functionality to set the expectations you require for your unit test.

On a slight aside, you also get the option of using a 'passive' EntityManager mock, in case you want to unit test a function which contains some database logic, but you don't actually want to go to the database in your unit test.

public function getPassiveEntityManagerMock() {    return \Mockery::mock('\Doctrine\ORM\EntityManager',                          array('getRepository' => new FakeRepository(),                                'getClassMetadata' => (object)array('name' => 'aClass'),                                'persist' => null,                                'flush' => null));}

Here's a suggested way of doing it with PHPUnit, but I haven't tried it out myself.


I ended up creating my own mock query builder; it may have been possible to get the same functionality using PHPUnits mocking framework but this is wha I ended up with:

<?phpnamespace MyNameSpace\Tests\Mocks;use Doctrine\ORM\QueryBuilder;use Doctrine\Common\Collections\ArrayCollection;class MockQueryBuilder extends QueryBuilder {    protected $expr;    protected $paramReflect;    public function __construct($expr) {        $this->expr = $expr;        $this->paramReflect = new \ReflectionProperty('Doctrine\ORM\QueryBuilder', 'parameters');         $this->paramReflect->setAccessible(true);        $this->paramReflect->setValue($this, new ArrayCollection());    }    /*     * @return Query\Expr     */    public function expr() {        return $this->expr;    }    public function getEntityManager() {        return null;    }    public function getQuery() {        return array(            'parameters' => clone $this->paramReflect->getValue($this),            'dql' => $this->getDQL(),        );    }}