首页 > 编程 > PHP > 正文

PHPUnit单元测试YAF模型层

2020-03-22 17:12:53
字体:
来源:转载
供稿:网友
  • 在Yaf应用中,创建一个模型层UserModel:

    <?phpClass UserModel {    // 初始化连接数据库,pre_common_member只有三条数据ID:1,2,3    html' target='_blank'>public function __construct() {        $this->_db = Core_LinkMySQL::get('hiapk_x2');    }     // 通过uid获取用户名,数据不存在时返回FALSE    public function fetchUsernameById($id) {        return $this->_db->select('username')            ->from('pre_common_member')            ->where('uid', $id)            ->fetchValue();    }     // 通过uid获取用户行数据,数据不存在时返回FALSE    public function fetchRowById($id) {        return $this->_db->select('username', 'groupid', 'adminid', 'regdate')            ->from('pre_common_member')            ->where('uid', $id)            ->fetchOne();    }}

    创建一个测试用例用于测试该模型层,需要几个条件:

    1.必须实例化Yaf_Application Final类;
    2.同时载入我们的Application必备的配置文件;
    3.官方文档有注明,Yaf_Application代表的是一个产品/项目,必须保证单例。

    基于以上3点,模型层的测试用例就很好编写了,创建一个Test Case:UserModelTest.php 该文件仅用于测试UserModel的业务。

            if ( ! self::$__model )            self::$__model = new UserModel();    }     // 测试 fetchRowById    public function testFetchRowById() {        $uid = 3;        $row = self::$__model->fetchRowById($uid);        $this->assertInternalType('array', $row);        $this->assertStringMatchesFormat('%s', $row['username']);        $this->assertStringMatchesFormat('%i', $row['groupid']);        $this->assertStringMatchesFormat('%i', $row['adminid']);        $this->assertStringMatchesFormat('%i', $row['regdate']);    }     // 测试 fetchUsernameById,由于我的数据表中只有3条数据,查询结果如果不存在是返回FALSE    public function testFetchUsernameById() {        $uid  = 4;        $name = self::$__model->fetchUsernameById($uid);        $this->assertInternalType('string', $name, $uid . ':' . gettype($name) );    }}


    测试结果:第二个Function由于查不到指定数据返回FALSE测试类型失败。PHP编程

    郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。

  • 发表评论 共有条评论
    用户名: 密码:
    验证码: 匿名发表