【问题标题】:How to properly delete an sqlite DB on a tearDown() in PHPUnit?如何在 PHPUnit 中的 tearDown() 上正确删除 sqlite DB?
【发布时间】:2019-06-14 05:11:23
【问题描述】:

这是一个使用setUp 和tearDown 方法的简化测试:

class FooTest extends TestCase
{
    private $dbFile;

    public function setUp()
    {
        $this->dbFile = 'test.db';

        if (!file_exists($this->dbFile)) {

            $pdo = new \PDO('sqlite:'.$this->dbFile);
            $pdo->query('
                CREATE TABLE `Users` (
                `id` INTEGER PRIMARY KEY AUTOINCREMENT,
                `foo` TEXT
            )');
        }
    }

    public function tearDown()
    {
        if (file_exists($this->dbFile))
            unlink($this->dbFile);
    }

    public function testFoo()
    {
        // ...
    }
}

这在理论上看起来不错,但我收到了 unlink(test.db): Text file busy 错误。

关于如何正确删除 PHPUnit 中 tearDown() 方法上的 sqlite DB 的任何想法?

【问题讨论】:

    标签: php sqlite unit-testing phpunit


    【解决方案1】:

    您可以使用内存模式,而不是使用 SQLite 文件数据库,其中“文件”仅为“:memory:”。这样您就不需要删除数据库文件。

    另见:https://www.sqlite.org/inmemorydb.html

    (但我不知道 SQLite 的 PHP 接口。)

    【讨论】:

    • 我认为这是一个不错的选择,但我找到了问题的答案。我需要 NULLify 连接,以便删除工作。
    【解决方案2】:

    对于那些关心的人,我找到了我的问题的答案:

    在删除 SQLite DB 之前,只需取消设置或取消 PDO 连接即可“关闭”它。

    unset($this->pdo); 或 $this->pdo = null;

    然后继续unlink();

    【讨论】:

      猜你喜欢
      • 2016-09-26
      • 2012-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-19
      • 1970-01-01
      • 2015-08-10
      • 2013-01-25
      相关资源
      最近更新 更多