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

时间:2015-07-01 09:31:42

标签: php mysql pdo phpunit

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

例如,这是我的https://api.linkedin.com/v1//people/~%3A%28first-name%2Clast-name%2Cemail-address%29?format=json&oauth2_access_token=

Could not find person based on: ~%3A%28first-name%2Clast-name%2Cemail-address%29

我想使用我用它进行开发和制作的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()
    {
    }
}

当我运行\app\source\Adaptor\PdoAdaptor.php来测试我的代码时,我收到此错误

  

致命错误:在null

上调用成员函数prepare()

<?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方法中的pdo根本没有实例化 - 我认为!

这是我的目录结构,

enter image description here

2 个答案:

答案 0 :(得分:2)

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

protected static $pdo;

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

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

答案 1 :(得分:1)

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

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