如果测试失败,在代码接收中如何回滚数据库?

问题描述 投票:0回答:3

我需要测试帐户中的功能。但是为此需要注册一个帐户。如果该功能无法正常运行并且测试失败,如何从数据库中自动删除帐户(测试期间创建的帐户)?

codeception
3个回答
1
投票

我认为您有一些选择。

您可以在Cest类的_before或_after方法中进行清理(例如,如果使用框架,则可以使用ORM删除所有帐户)。

Codeception的Db模块(请参阅https://codeception.com/docs/modules/Db)也具有清除标志,当该标志为true时,它将在每次测试之前加载用户定义的数据库转储(您可以创建没有帐户的转储)。

可能还有其他选择。例如,如果您使用Yii2,则用于Codeception的Yii2模块具有清除标志,如果为true,该标志将在测试中包装测试(请参见https://codeception.com/for/yii)。


0
投票

我们也面临着这样的问题。如果您将帐户插入带有codception的DB模块,则可以使用cleanup标志,它将在每次运行后自动清除数据库。

如果通过测试创建帐户,并且要确保在开始测试之前不存在该帐户,则可以通过删除功能扩展数据库模块(必须谨慎使用,我们仅允许在测试环境中)。

<?php

namespace Helper\Shared;

class DbHelper extends \Codeception\Module {

    public function deleteFromDatabase($table, $criteria)
    {
        $dbh = $this->getModule('Db')->_getDbh();
        $query = "delete from `%s` where %s";
        $params = [];
        foreach ($criteria as $x => $y) {
            $params[] = "`$x` = '$y'";
        }
        $params = implode(' AND ', $params);
        $query = sprintf($query, $table, $params);
        codecept_debug($query);
        $this->debugSection('Query', $query, json_encode($criteria));
        $sth = $dbh->prepare($query);
        return $sth->execute(array_values($criteria));
    }
}

这可以在测试代码中使用...

$I->deleteFromDatabase('account', ['id' => '123456']);

如果可能,应使用数据库模块创建帐户并再次清理。上面的这种方法非常危险,取决于您所使用的系统。


0
投票

[您好,我亲爱的用户153742。以我的理解,您已经要求一种立即回滚角色数据库的方法。对不起,我不知道该怎么做。但是我知道一种在每个函数中创建实体的每个实例之后,删除插入的实体的方法。为此,您需要使用“ removeInserted(')方法。让我给你看一个例子,看看:

 <?php
    public function shouldCreateNewOrder(AcceptanceTester $I){
            try {
                $fields = $this->orderCreatePage->createNewOrder();
                $I->see(OrderListPage::MESSAGE_REGISTRATION_SUCCEDED);

                OrderListPage::go($I)->clickSearchButton();
                OrderListPage::go($I)->clickDeleteButton();
                OrderListPage::go($I)->clickConfirmButton();

            }catch(\Exception $e){
                $I->removeInserted(); // the most one like a "rollback" function that I found!
                $I->see(OrderListPage::ERROR_MESSAGE_ALREADY_ORDERED);
            }  
        }
    ?>
© www.soinside.com 2019 - 2024. All rights reserved.