(一)利用单元测试在每个层上对 PHP 代码进行检查

发表于:2007-8-07 14:27  作者:Jack D. Herrington   来源:网络转载

字体: | 上一篇 | 下一篇 |我要投稿 | 推荐标签:

清单 7. 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()
  {
    return false;
  }
  public static function insert( $name )
  {
    return false;
  }
  public static function get_all()
  {
    return null;
  }
}
?>
 
对清单 8 中的代码执行单元测试会显示这 3 个测试全部失败了:
清单 8. dblib.php

% phpunit TestAuthors.php
PHPUnit 2.2.1 by Sebastian Bergmann.

FFF

Time: 0.007500171661377
There were 3 failures:
1) test_delete_all(TestAuthors)

2) test_insert(TestAuthors)

3) test_insert_and_get(TestAuthors)


FAILURES!!!
Tests run: 3, Failures: 3, Errors: 0, Incomplete Tests: 0.
%
 
        现在我们可以开始添加正确访问数据库的代码 —— 一个方法一个方法地添加 —— 直到所有这 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;
  }
}
?>
 
        在对这段代码运行测试时,所有的测试都可以没有问题地运行,这样我们就可以知道自己的代码可以正确工作了。


33/3<123

评 论

论坛新帖



建议使用IE 6.0以上浏览器,800×600以上分辨率,法律顾问:上海信义律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2022, 沪ICP备05003035号
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪公网安备 31010102002173号

51Testing官方微信

51Testing官方微博

扫一扫 测试知识全知道