1

我有一个功能测试,它在数据库中创建和保留一些东西,我想测试插入的项目数量是否正确(有一种情况是它当前插入两个而不是一个)。

在控制器中,一切似乎都正常工作,如果我使用下面的代码(在控制器中)进行调试,我会得到“2”的预期(错误)值:

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

但是,如果我在我的测试课程中尝试类似的东西,我会得到零......

/**
 * {@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
}

是否获得了不同的实体经理或类似的东西?我是否应该使用其他方法来获取正确的 EM,以便我可以查看应用程序正在运行的相同数据?

一切都在事务中运行(当测试客户端被销毁时会回滚),但这发生在上面显示的代码片段之后。

4

1 回答 1

1

啊...解决了我自己的问题。我想我弄错了EntityManager。我通过客户端的容器而不是内核的容器获取 EntityManager 来修复它:

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
}
于 2013-10-16T21:26:26.493 回答