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 SuiteTes
t - I think!
This is my dir structure,
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.
You should use the setup method instead of overwriting the PHPUnit_Framework_TestCase constructor, ie just replace the constructor definition in SuiteTest class with:
public function setup()
{
$this->PDO = new \Foo\Adaptor\PdoAdaptor();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.