PHPUnit - 如何在 PHPUnit_Framework_TestCase 中实例化我的 pdo class?

PHPUnit - How to instantiate my pdo class in PHPUnit_Framework_TestCase?

如何在 PHPUnit_Framework_TestCase 中实例化我的 pdo class?

例如,这是我的 \test\SuitTest.php,

namespace Test;

use PHPUnit_Framework_TestCase;

class SuiteTest extends PHPUnit_Framework_TestCase
{
    protected $PDO = null;

    public function __construct()
    {
        parent::__construct();
        $this->PDO = new \Foo\Adaptor\PdoAdaptor(); // the pdo is not instantiated at all - I think!
    }

    protected function truncateTables ($tables)
    {
        foreach ($tables as $table) {
            $this->PDO->truncateTable($table);
        }
    }

    /**
     * DO NOT DELETE, REQUIRED TO AVOID FAILURE OF NO TESTS IN FILE
     * PHPUnit is ignoring the exclude in the phpunit.xml config file
     */
    public function testDummyTest()
    {
    }
}

我想使用我用于开发和生产的 pdo class,它位于 \app\source\Adaptor\PdoAdaptor.php,

<?php

namespace Foo\Adaptor;

use PDO;

class PdoAdaptor
{
    protected $PDO = null;
    protected $dsn = 'mysql:host=localhost;dbname=phpunit', $username = 'root', $password = 'xxxx';

    /*
     * Make the pdo connection.
     * @return object $PDO
     */
    public function connect()
    {
        try {
            $this->PDO = new PDO($this->dsn, $this->username, $this->password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
            $this->PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            // Unset props.
            unset($this->dsn);
            unset($this->username);
            unset($this->password);
        } catch (PDOException $error) {
            // Call the getError function
            $this->getError($error);
        }
    }

    public function truncateTable($table)
    {
        $sql = "TRUNCATE TABLE $table";
        $command = $this->PDO->prepare($sql);
        $command->execute();
    }
}

当我 运行 phpunit 测试我的代码时出现此错误,

Fatal error: Call to a member function prepare() on null

pdo 根本没有在 SuiteTest 中的 construct 方法中实例化 - 我认为!

这是我的目录结构,

您应该使用设置方法而不是覆盖 PHPUnit_Framework_TestCase 构造函数,即只需将 SuiteTest class 中的构造函数定义替换为:

public function setup()
{
    $this->PDO = new \Foo\Adaptor\PdoAdaptor();
}

使用setUpBeforeClass方法(注意:它是静态的)

protected static $pdo;

public static function setUpBeforeClass()
{
    static::$pdo = new PdoAdapter();
}

然后只需在测试中使用 static::$pdoself::$pdo 访问您的 pdo 实例。