Ugly code unit testing with PHPUnit and Doctrine2 (an ORM)
I decided that there was too much database access code in my UserPermissions class and split it into two classes.  The first class is now much easier to mock and the second class is just a wrapper for a doctrine query, which is probably almost pointless to mock.

class UserPermissions{

    protected $dbalUserProducts;

    public function __construct($dbalUserProducts){
        $this-&gt;dbalUserProducts= $dbalUserProducts;
    }

    /**
     * returns user's permissions for all products or specific product
     **/
    public function get($userId, $productId=NULL){

        $userProducts = $this-&gt;dbalUserProducts-&gt;get($userId, $productId);

        $result = [];

        for ($i = 0; $i &lt; count($userProducts); $i++) {
            $up = $userProducts[$i];
            array_push($result, array(
                "product" =&gt; $up-&gt;getProduct()-&gt;getId(),
                "permissions" =&gt; $up-&gt;getPermissions(),
            ));
        }

        return $result;
    }
}




class UserProductQuery
{
    protected $em;

    public function __construct($entityManager)
    {
        $this-&gt;em = $entityManager;
    }

    public function get($userId=null, $productId=null){
        $qb = $this-&gt;em-&gt;createQueryBuilder();

        $qb-&gt;select('u')
           -&gt;from('\MyProject\Entity\UserProduct', 'u');

        if ($userId) {
            $qb-&gt;andWhere($qb-&gt;expr()-&gt;eq('u.user', ':userId'));
            $qb-&gt;setParameter('userId',$userId);
        }
        if ($productId) {
            $qb-&gt;andWhere($qb-&gt;expr()-&gt;eq('u.product', ':productId'));
            $qb-&gt;setParameter('productId',$productId);
        }

        return($qb-&gt;getQuery()-&gt;getResult());
    }
}