您的位置:軟件測試 > 開源軟件測試 > 開源單元測試工具 > PHPUnit
利用PHPUnit單元測試對PHP代碼進行檢查
作者:網(wǎng)絡轉載 發(fā)布時間:[ 2014/1/2 13:13:06 ] 推薦標簽:PHPUnit 代碼 檢查

    現(xiàn)在我們可以開始添加正確訪問數(shù)據(jù)庫的代碼 —— 一個方法一個方法地添加 —— 直到所有這 3 個測試都可以通過。終版本的 dblib.php 代碼如下所示。


清單 9. 完整的 dblib.php

<?php
require_once('DB.php');

class Authors
{
public static function get_db()
{
$dsn = 'mysql://root:password@localhost/unitdb';
$db =& DB::Connect( $dsn, array() );
if (PEAR::isError($db)) { die($db->getMessage()); }
return $db;
}
public static function delete_all()
{
$db = Authors::get_db();
$sth = $db->prepare( 'DELETE FROM authors' );
$db->execute( $sth );
return true;
}
public static function insert( $name )
{
$db = Authors::get_db();
$sth = $db->prepare( 'INSERT INTO authors VALUES (null,?)' );
$db->execute( $sth, array( $name ) );
return true;
}
public static function get_all()
{
$db = Authors::get_db();
$res = $db->query( "SELECT * FROM authors" );
$rows = array();
while( $res->fetchInto( $row ) ) { $rows []= $row; }
return $rows;
}
}
?>

HTML 測試

    對整個 PHP 應用程序進行測試的下一個步驟是對前端的超文本標記語言(HTML)界面進行測試。要進行這種測試,我們需要一個如下所示的 Web 頁面。

這個頁面對兩個數(shù)字進行求和。為了對這個頁面進行測試,我們首先從單元測試代碼開始入手。


清單 10. TestPage.php

<?php
require_once 'HTTP/Client.php';
require_once 'PHPUnit2/Framework/TestCase.php';

class TestPage extends PHPUnit2_Framework_TestCase
{
function get_page( $url )
{
$client = new HTTP_Client();
$client->get( $url );
$resp = $client->currentResponse();
return $resp['body'];
}
function test_get()
{
$page = TestPage::get_page( 'http://localhost/unit/add.php' );
$this->assertTrue( strlen( $page ) > 0 );
$this->assertTrue( preg_match( '/<html>/', $page ) == 1 );
}
function test_add()
{
$page = TestPage::get_page( 'http://localhost/unit/add.php?a=10&b=20' );
$this->assertTrue( strlen( $page ) > 0 );
$this->assertTrue( preg_match( '/<html>/', $page ) == 1 );
preg_match( '/<span id="result">(.*?)</span>/', $page, $out );
$this->assertTrue( $out[1]=='30' );
}
}
?>

上一頁123456下一頁
軟件測試工具 | 聯(lián)系我們 | 投訴建議 | 誠聘英才 | 申請使用列表 | 網(wǎng)站地圖
滬ICP備07036474 2003-2017 版權所有 上海澤眾軟件科技有限公司 Shanghai ZeZhong Software Co.,Ltd