您的位置:軟件測(cè)試 > 開(kāi)源軟件測(cè)試 > 開(kāi)源單元測(cè)試工具 > PHPUnit
利用PHPUnit單元測(cè)試對(duì)PHP代碼進(jìn)行檢查
作者:網(wǎng)絡(luò)轉(zhuǎn)載 發(fā)布時(shí)間:[ 2014/1/2 13:13:06 ] 推薦標(biāo)簽:PHPUnit 代碼 檢查

    現(xiàn)在我們可以開(kāi)始添加正確訪問(wèn)數(shù)據(jù)庫(kù)的代碼 —— 一個(gè)方法一個(gè)方法地添加 —— 直到所有這 3 個(gè)測(cè)試都可以通過(guò)。終版本的 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 測(cè)試

    對(duì)整個(gè) PHP 應(yīng)用程序進(jìn)行測(cè)試的下一個(gè)步驟是對(duì)前端的超文本標(biāo)記語(yǔ)言(HTML)界面進(jìn)行測(cè)試。要進(jìn)行這種測(cè)試,我們需要一個(gè)如下所示的 Web 頁(yè)面。

這個(gè)頁(yè)面對(duì)兩個(gè)數(shù)字進(jìn)行求和。為了對(duì)這個(gè)頁(yè)面進(jìn)行測(cè)試,我們首先從單元測(cè)試代碼開(kāi)始入手。


清單 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' );
}
}
?>

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