Question

I am writing codeception unit tests for a Manager class in my Symfony2 application, and I am wondering how to mock the entity manager. For example, let's say I have the following function in my AcmeManager service class:

<?php

namespace Acme\AcmeBundle\Manager;

use Doctrine\Common\Persistence\ObjectManager;

class AcmeManager
{
    private $em;

    public function __construct (ObjectManager $em)
    {
         $this->em = $em;
    }

    public function findMatches($index)
    {
        // Find and display matches.
        $matches = $this->em
            ->getRepository('AcmeBundle:AssignMatch')
            ->findBy(array('assignIndex' => $index));

        return $matches;
    }
}

and I wanted to write the following test function:

<?php

use Codeception\Util\Stub;

class AutoManagerTest extends \Codeception\TestCase\Test
{
    /**
     * @var \CodeGuy
     */
    protected $codeGuy;

    protected function _before()
    {
    }

    protected function _after()
    {
    }
    /**
     * Tests findMatches($index).
     */
    public function testFindMatches()
    {
        //...  $mockedEntityManager is our mocked em
        $acmeManager = $this->getModule('Symfony2')->container->get('acme_manager');
        $acmeManager->findMatches(0);
        // $this->assert(isCalled($mockedEntityManager));
    }
}

How can I mock the entity manager such that when I call $acmeManager->findMatches(0);, I can assert that the mocked entity manager is called (even though $acmeManager uses the regular Symfony2 entity manager in its normal implementation)?

Was it helpful?

Solution

I think the easiest way would be to skip the DIC part and simply instantinate the AcmeManager with the EM passed in the constructor.

The other way would be getting it from the DIC as you currently do, and setting AcmeManager::$em with reflection. Something like this:

$acmeManager = $this->getModule('Symfony2')->container->get('acme_manager');
$class = new \ReflectionClass('\Acme\AcmeBundle\Manager\AcmeManager');
$property = $reflection->getProperty('em');
$property->setAccessible(true);
$property->setValue($acmeManager, $mockedEntityManager);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top