douji1058
2015-07-01 09:31
浏览 39
已采纳

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

How can I instantiate my pdo class in PHPUnit_Framework_TestCase?

for instance, this is my \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()
    {
    }
}

I want to use the pdo class that I use it for development and production, which is in, \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();
    }
}

I get this error when I run phpunit for testing my codes,

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

The pdo is not instantiated at all inside the construct method in SuiteTest - I think!

This is my dir structure,

enter image description here

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • drx3157 2015-07-01 12:27
    已采纳

    Use the setUpBeforeClass method (note: it's static)

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

    Then just access your pdo instance with static::$pdo or self::$pdo in your tests.

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • doue2666 2015-07-01 12:23

    You should use the setup method instead of overwriting the PHPUnit_Framework_TestCase constructor, i.e. just replace the constructor definition in SuiteTest class with:

    public function setup()
    {
        $this->PDO = new \Foo\Adaptor\PdoAdaptor();
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题