簡體   English   中英

PHPUnit-如何在PHPUnit_Framework_TestCase中實例化我的pdo類?

[英]PHPUnit - How to instantiate my pdo class in PHPUnit_Framework_TestCase?

如何在PHPUnit_Framework_TestCase中實例化我的pdo類?

例如,這是我的\\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類,位於\\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來測試我的代碼時出現此錯誤,

致命錯誤:在null上調用成員函數prepare()

SuiteTes t的construct方法中SuiteTes沒有實例化SuiteTes我想!

這是我的目錄結構,

在此處輸入圖片說明

使用setUpBeforeClass方法(注意:它是靜態的)

protected static $pdo;

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

然后只需在測試中使用static::$pdoself::$pdo訪問您的pdo實例。

您應該使用setup方法,而不是覆蓋PHPUnit_Framework_TestCase構造函數,即僅將SuiteTest類中的構造函數定義替換為:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM