本文介绍了PHPUnit和MySQL截断错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对PHPUnit始终运行TRUNCATE在插入固定装置而没有首先关闭外键检查之前始终运行TRUNCATE的行为感到头痛:

I am getting a headache with PHPUnit's behavior of always running TRUNCATE prior to inserting fixtures without first setting foreign key checks off:

Syntax error or access violation: 1701 Cannot truncate a table referenced in a foreign key constraint

基本上,PHPUnit会在插入固定装置之前尝试截断表.如何将其告知SET FOREIGN_KEY_CHECKS=0;?

Basically, PHPUnit tries to truncate a table before it inserts fixtures. How do I tell it to SET FOREIGN_KEY_CHECKS=0;?

推荐答案

我找到了答案.我最终通过扩展类重写了一些方法.

I found the answer it seems. I ended up overriding some methods by extending a class.

<?php

/**
 * Disables foreign key checks temporarily.
 */
class TruncateOperation extends \PHPUnit_Extensions_Database_Operation_Truncate
{
    public function execute(\PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection, \PHPUnit_Extensions_Database_DataSet_IDataSet $dataSet)
    {
        $connection->getConnection()->query("SET foreign_key_checks = 0");
        parent::execute($connection, $dataSet);
        $connection->getConnection()->query("SET foreign_key_checks = 1");
    }
}

然后是示例用法:

class FooTest extends \PHPUnit_Extensions_Database_TestCase
{
    public function getSetUpOperation()
    {
        $cascadeTruncates = true; // If you want cascading truncates, false otherwise. If unsure choose false.

        return new \PHPUnit_Extensions_Database_Operation_Composite(array(
            new TruncateOperation($cascadeTruncates),
            \PHPUnit_Extensions_Database_Operation_Factory::INSERT()
        ));
    }
}

因此,我有效地禁用了外键检查,并将它们重新设置(如果曾经设置过的话).显然,您应该创建一个具有此功能的基类,然后扩展它而不是PHPUnit的TestCase.

So I'm effectively disabling foreign key checks and setting them back if they were ever set. Obviously you should make a base class that has this functionality and you extend it rather than PHPUnit's TestCase.

这篇关于PHPUnit和MySQL截断错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 16:49