2013-10-16 45 views
1

我有一個功能測試,在數據庫中創建並保留了一些東西,我想測試是否插入了正確數量的項目(當前插入兩個而不是一個)。symfony測試數據庫插入

在控制一切似乎工作,如果我用下面的代碼(控制器),調試它,我得到的「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,以便我可以查看應用程序運行的相同數據?

一切都在事務內部運行(當測試客戶端被銷燬時會回退),但發生在上面顯示的代碼片段之後。

回答

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 
}