[英]PHPUnit - How to instantiate my pdo class in PHPUnit_Framework_TestCase?
How can I instantiate my pdo class in PHPUnit_Framework_TestCase? 如何在PHPUnit_Framework_TestCase中实例化我的pdo类?
for instance, this is my \\test\\SuitTest.php
, 例如,这是我的
\\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
, 我想使用用于开发和生产的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();
}
}
I get this error when I run phpunit
for testing my codes, 当我运行
phpunit
来测试我的代码时出现此错误,
Fatal error: Call to a member function prepare() on null
致命错误:在null上调用成员函数prepare()
The pdo is not instantiated at all inside the construct
method in SuiteTes
t - I think! 在
SuiteTes
t的construct
方法中SuiteTes
没有实例化SuiteTes
我想!
This is my dir structure, 这是我的目录结构,
Use the setUpBeforeClass
method (note: it's static) 使用
setUpBeforeClass
方法(注意:它是静态的)
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. 然后只需在测试中使用
static::$pdo
或self::$pdo
访问您的pdo实例。
You should use the setup method instead of overwriting the PHPUnit_Framework_TestCase constructor, ie just replace the constructor definition in SuiteTest class with: 您应该使用setup方法,而不是覆盖PHPUnit_Framework_TestCase构造函数,即仅将SuiteTest类中的构造函数定义替换为:
public function setup()
{
$this->PDO = new \Foo\Adaptor\PdoAdaptor();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.