无法设置夹具(带有dbunit的PHPunit)

时间:2018-10-11 00:20:53

标签: phpunit phalcon fixtures dbunit

尝试为我的Phalcon测试设置固定装置,但失败。 您能找出我的实现方式出了什么问题吗?

用法

  • 猎鹰7.2
  • Docker版本18.09.0-ce-beta1
  • docker-compose版本1.22.0
  • phpunit6.5.8
  • dbunit 3.0.3

当前状态

  • 使用“ getConnection”功能连接到数据库成功

  • 创建dataSet(YAML类型)

  • 创建getDataSet函数,但无法设置固定装置并进行清理

unitTestCase.php

<?php

use Phalcon\Di;
use Phalcon\Mvc\Model\Manager as ModelsManager;
use Phalcon\Test\UnitTestCase as PhalconTestCase;
use PHPUnit\DbUnit\TestCaseTrait;

require_once "CustomHelper.php";

// config of phpunit

abstract class UnitTestCase extends PhalconTestCase
{
use TestCaseTrait;

/**
 * @var bool
 */
private $_loaded = false;

public function setUp()
{
    parent::setUp();

    $di = Di::getDefault();

    $di->set(
        "modelsManager",
        function () {
            return new ModelsManager();
        }
    );
    $di["modelsMetadata"] = function () {
        $metadata = new \Phalcon\Mvc\Model\Metadata\Files(
            [
                "metaDataDir" => joinPaths(__DIR__, "/path/to/metadata/"),
            ]
        );

        return $metadata;
    };
    $di->setShared('mockControllerHelper', new mockControllerHelper());
    $di->setShared('helper', new Helpers());
    $di->setShared('config', function () {
        return require CONFIG_DIR . 'app.php';
    });

    $di->setShared('db', function () {
        $config = $this->getConfig();

        // database configuration from app.php
        $class = 'Phalcon\Db\Adapter\Pdo\\' . $config->database->adapter;
        $params = [
            'host' => $config->database->host,
            'username' => $config->database->username,
            'password' => $config->database->password,
            'dbname' => $config->database->dbname,
        ];

        if ($config->database->adapter == 'Postgresql') {
            unset($params['charset']);
        }

        $connection = new $class($params);

        return $connection;
    });
    $this->setDi($di);

    $this->_loaded = true;
}

public function tearDown()
{
    /* This static call cleans up the Mockery container used by the current test, and run any verification tasks needed for our expectations. */
    \Mockery::close();
}

/**
 * Check if the test case is setup properly
 *
 * @throws \PHPUnit_Framework_IncompleteTestError;
 */
public function __destruct()
{
    if (!$this->_loaded) {
        throw new \PHPUnit_Framework_IncompleteTestError(
            "Please run parent::setUp()."
        );
    }
}



 // Setting part of dbunit
static private $pdo = null;

private $conn = null;

final public function getConnection()
{
    require CONFIG_DIR . 'app.php';
    if ($this->conn === null) {
        if (self::$pdo == null) {
            self::$pdo = new PDO(
                'mysql:host='. $globalConfig->database->host .';dbname=test',
                $globalConfig->database->username,
                $globalConfig->database->password
            );
        }
        $this->conn = $this->createDefaultDBConnection(self::$pdo, 'dbname=test');
    }

     return $this->conn;
}

}

TestControllerTest.php

<?php

namespace Test\Controllers;

use PHPUnit\DbUnit\DataSet\YamlDataSet;

class DatabaseTest extends \UnitTestCase
{
    protected function getDataSet()
    {
        return new YamlDataSet(__DIR__ . "/../DataSet/dataSet.yml");
    }

    public function testsTableRow() {
        $this->assertEquals(1, $this->getConnection()->getRowCount('testRow'), "");
    }
}

数据集

testRow:
  -
    id: 1
    name: 'test'
    text: 'hello, world'

响应

Failed asserting that 0 matches expected 1.

注意

当我在getConnection中使用真实的mysql数据库连接并调用$this->getConnection()->getRowCount('testRow')时,结果是正确的。 因此,问题似乎来自加载yaml数据集

supplementation1

$this->getConnection的内容是:

(执行print_r($this->getConnection(), false);

(                                                                                                                                             
    [connection:protected] => PDO Object                                                                                                      
        (                                                                                                                                     
        )                                                                                                                                     

    [metaData:protected] => PHPUnit\DbUnit\Database\Metadata\MySQL Object                                                                     
        (                                                                                                                                     
            [schemaObjectQuoteChar:protected] => `                                                                                            
            [pdo:protected] => PDO Object                                                                                                     
                (                                                                                                                             
                )                                                                                                                             

            [schema:protected] => dbname=test                                                                                         
            [truncateCommand:protected] => TRUNCATE                                                                                           
        )
)

$this->getDataSet()的内容是:

(执行print_r($this->getDataSet(), false);

(                                                                                                                                             
    [tables:protected] => Array                                                                                                               
        (                                                                                                                                     
            [testRow] => PHPUnit\DbUnit\DataSet\DefaultTable Object                                                                           
                (                                                                                                                             
                    [tableMetaData:protected] => PHPUnit\DbUnit\DataSet\DefaultTableMetadata Object                                           
                        (                                                                                                                     
                            [columns:protected] => Array                                                                                      
                                (                                                                                                             
                                    [0] => id                                                                                                 
                                    [1] => name                                                                                               
                                    [2] => text                                                                                               
                                )                                                                                                             

                            [primaryKeys:protected] => Array                                                                                  
                                (                                                                                                             
                                )                                                                                                             

                            [tableName:protected] => testRow                                                                                  
                        )                                                                                                                     

                    [data:protected] => Array                                                                                                 
                        (                                                                                                                     
                            [0] => Array                                                                                                      
                                (                                                                                                             
                                    [id] => 1                                                                                                 
                                    [name] => test
                                    [text] => hello, world
                                )

                        )

                    [other:PHPUnit\DbUnit\DataSet\AbstractTable:private] =>
                )

        )

    [parser:protected] => PHPUnit\DbUnit\DataSet\SymfonyYamlParser Object
        (
        )

)

1 个答案:

答案 0 :(得分:1)

Dbunit必须执行一些设置操作,并且它们在PHPUnit\DbUnit\TestCaseTrait方法的setUp()中进行了定义(您可以看到更多的code details here。在继承PHPUnit\DbUnit\TestCase时,您基本上不需要不必担心(除了确保从测试用例中调用parent::setUp()之外),当直接从trait中使用功能时,必须确保也调用了dbunit的设置。 您可以通过如下方式实现此目标:

<?php
use Phalcon\Test\UnitTestCase as PhalconTestCase;
use PHPUnit\DbUnit\TestCaseTrait;

abstract class UnitTestCase extends PhalconTestCase
{
    use TestCaseTrait {
        setUp as protected dbunitSetUp;
    };

    public function setUp()
    {
        parent::setUp(); // phalcon setup
        $this->dbuintSetUp(); // dbunit setup
    }
}

对于上面的示例,仅包括与问题相关的行,并跳过诸如getConnection之类的其他内容。