Pregunta

I have a functional test that creates and persists some things in the database and I want to test that the correct number of items was inserted (there is a scenario where it currently inserts two instead of one).

In the controller everything seems to work and if I use the code below (in the controller) to debug it, I get the expected (wrong) value of "2":

$em = $this->getDoctrine()->getManager();
$fooRepo = $em->getRepository('CompanyProjectBundle:Foo');
$foos = $fooRepo->retrieveByBar(3);
echo count($foos); // Gives a result of 2

However, if I try something similar from within my Test class I get zero...

/**
 * {@inheritDoc}
 */
protected function setUp()
{
    static::$kernel = static::createKernel();
    static::$kernel->boot();
    $this->em = static::$kernel->getContainer()
        ->get('doctrine')
        ->getManager()
    ;
    $this->em->getConnection()->beginTransaction();
}

/**
 * {@inheritDoc}
 */
protected function tearDown()
{
    parent::tearDown();
    $this->em->getConnection()->rollback();
    $this->em->close();
}

public function testFooForm()
{
    // ... do some testing

    $fooRepo = $this->em->getRepository('CompanyProjectBundle:Foo');
    $foos = $fooRepo->retrieveByBar(3);
    echo count($foos); // gives a result of ZERO

    // ... more happens later
}

Is it getting a different entity manager or something like that? Should I be using some other method to get hold of the correct EM so I can then view the same data that the app is running from?

Everything's running inside a transaction (which is rolled back when the test client is destroyed), but that happens after the snippet shown above.

¿Fue útil?

Solución

Ah... solved my own problem. I think I was getting the wrong EntityManager. I fixed it by getting the EntityManager via the client's container instead of the kernel's one:

public function testFooForm()
{
    // ... do some testing

    $clientEm = $client->getContainer()->get('doctrine.orm.entity_manager');
    $fooRepo = $clientEm->getRepository('CompanyProjectBundle:Foo');
    $foos = $fooRepo->retrieveByBar(3);
    echo count($foos); // gives the correct result of 2

    // ... more happens later
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top