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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用