先要配到数据库参数,在phpunit.xml中定义,这个文件在使用phpunit时会自动加载
首先要实现一个类来创建数据库连接,以及初始化数据库
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
abstract class Generic_Tests_DatabaseTestCase extends PHPUnit_Extensions_Database_TestCase
{
//只实例化PDO一次,供测试的清理和基境读取使用
static private $pdo = null;
//对于每个测试,只实例化一次
private $conn = null;
final public function getConnection()
{
if($this->conn === null){
if(self::$pdo == null){//这里的$GLOBALS都是在phpunit.xml文件中定义的
self::$pdo = new PDO($GLOBALS['DB_UNIT'],$GLOBALS['DB_USER'],$GLOBALS['DB_PASSWD']);
}
$this->conn = $this->createDefaultDBConnection(self::$pdo);
}
return $this->conn;
}
public function getDataSet()
{
//导出为xml格式数据库
//return $this->createMySQLXMLDataSet('./nn_cms.xml');
//直接使用数组创建数据库基境
return $this->createArrayDataSet(array(
'guestbook' => array(
array('id' => 1, 'content' => 'Hello buddy!', 'user' => 'joe', 'created' => '2010-04-24 17:15:23'),
array('id' => 2, 'content' => 'I like it!', 'user' => null, 'created' => '2010-04-26 12:14:20'),
),
));
}
}
测试数据库:只到运行了下面三个测试中的其中一个,数据库都会重建。故在进行phpunit的测试前,先运行一个dbunit的测试(或将该测试加入测试套件),即可使建立数据库基境。
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
include_once './pdotest.php';
class ConnectionTest extends Generic_Tests_DatabaseTestCase
{
public function testCreateDataSet()
{
$tableNames = array('guestbook');
$dataSet = $this->getConnection()->createDataSet();
}
public function testCreateQueryTable()
{
$tableNames = array('guestbook');
$queryTable = $this->getConnection()->createQueryTable('guestbook', 'select * from guestbook');
}
public function testGetRowCount()
{
$this->assertEquals(2, $this->getConnection()->getRowCount('guestbook'));
$this->assertEquals(2, $this->getConnection()->getRowCount('guestbook'));
}
}