您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
phpunit数据库测试-通过phpunit.xml连接mysql
发布时间:2021-09-26 23:13:34编辑:雪饮阅读()
就说上篇优化了数据库的连接,但是那个连接是对于sqlite的,实际上我们主要常用的还是mysql。
<testsuites>
<testsuite name="Database">
<file>tests/UserTest.php</file>
<file>tests/DatabaseTest.php</file>
<file>tests/InvoiceTest.php</file>
</testsuite>
</testsuites>
<php>
<var name="DB_DSN" value="mysql:dbname=myguestbook;host=localhost" />
<var name="DB_USER" value="root" />
<var name="DB_PASSWD" value="123456" />
<var name="DB_DBNAME" value="myguestbook" />
</php>
</phpunit>
use PHPUnit\Framework\TestCase;
use PHPUnit\DbUnit\TestCaseTrait;
abstract class MyAppTestsDatabaseTestCase extends TestCase
{
use TestCaseTrait;
static private $pdo = null;
private $conn = null;
final public function getConnection()
{
if ($this->conn === null) {
if (self::$pdo == null) {
self::$pdo = new PDO( $GLOBALS['DB_DSN'], $GLOBALS['DB_USER'], $GLOBALS['DB_PASSWD'] );
}
$this->conn = $this->createDefaultDBConnection(self::$pdo, $GLOBALS['DB_DBNAME']);
}
return $this->conn;
}
public function getDataSet()
{
return $this->createFlatXMLDataSet(dirname(__FILE__).'/_files/guestbook-seed.xml');
}
}
class MyAppTestsDatabaseTestCaseImplement extends MyAppTestsDatabaseTestCase{
public function testConnect(){
$l_conn=$this->getConnection();
var_dump($l_conn);
}
}
接下来你要按照phpunit中配置的数据库名、数据库地址、连接用户名、连接用户名对应密码去mysql中准备一番,除了这些准备外还要准备一张表,为什么呢?
也就是说getDataSet其实就是获取数据集的配置来源,这里就是guestbook-seed.xml,从该来源中像当前实现的getConnection中填充数据。
<dataset>
<guestbook id="1" content="Hello buddy!" user="joe" created="2010-04-24 17:15:23" />
<guestbook id="2" content="我喜欢!" user="nancy" created="2010-04-26 12:14:20" />
</dataset>
关键字词:phpunit,mysql