Symfony2 - 测试Doctrine Listener

时间:2014-11-14 16:41:40

标签: php symfony doctrine-orm doctrine phpunit

我已经在教条事件(持久,更新和删除)上创建了一个监听器,可以在远程数据库中保存所有操作(模式:谁做什么,何时,旧值,新值 )。

有效。

为了进行持续集成,我通过在每次操作后检索这些日志来编写一些单元测试。

/**
 * @param $uid      user id
 * @param $isValid  is user need to be added 
 */
public function testGetLogs($uid, $isValid) {

    $um = static::$kernel->getContainer()->get('user_manager');

    /** @var EntityManager $em */
    $em = $this->doctrine->getManager();
    $referentielUser = $um->getReferentielUser($uid);

    // Lazy method to retrieve application's identifiers
    $auditDummy = new AuditEntry();
    $dir = $auditDummy->getAppDir();
    $host = $auditDummy->getAppHost();

    if (false !== $referentielUser) {
        $user = $referentielUser->toUser();
        // add the user
        $valid = $um->addUser($user);
    } else {
        $valid = false;
    }

    $this->assertEquals($isValid, $valid);

    if ($valid) {
        // find latest logs for insertion
        $logs = array_reverse($this->doctrineListener->getLogs(array('appdir'=>$dir, 'apphost'=>$host)));
        $this->logTesting($logs[0], 'insert');

        // edit the user
        $user->setLocked(true);
        $em->commit();

        // find latest logs for edition
        $logs = array_reverse($this->doctrineListener->getLogs(array('appdir'=>$dir, 'apphost'=>$host)));
        $this->logTesting($logs[0], 'update');

        // remove the user
        $em->remove($user);
        $em->commit();

        // find latest logs for removal
        $logs = array_reverse($this->doctrineListener->getLogs(array('appdir'=>$dir, 'apphost'=>$host)));
        $this->logTesting($logs[0], 'delete');

    }

}

private function logTesting($log, $type) {
    $this->assertEquals(/* Folder */, $log['APPDIR']);
    $this->assertEquals('cli', $log['IP']);
    $this->assertEquals(/* Table */, $log['TARGETTABLE']);
    $this->assertEquals(strtoupper($type), $log['ACTION']);

    $dateLog = date_create_from_format('Y-m-d H:i:s', $log['DATETIME']);
    $diff = $dateLog->diff(new \DateTime());
    $this->assertLessThan(5, $diff->s);
}

用户已正确添加但未编辑或删除。 你能帮我吗?

1 个答案:

答案 0 :(得分:0)

您应该使用$em->flush()使Doctrine对数据库执行查询,而不是$em->commit