yaf框架单元测试

代码目录结构:

项目目录
  application     控制器和视图目录
  configs         ini配置文件目录
  library         Dao、Model、Service层目录
  public          入口文件目录
  tests           单元测试目录
    api           测试用例目录
    bootstrap.php  单元测试初始化文件
  vendor          第三方库(composer)
  composer.json   composer依赖文件
  phpunit.xml     单元测试配置文件

在yaf中做单元测试,主要是测试library下面的库,包括Dao、Model、Service层的测试。

controller层一般通过API功能测试,这个不依赖yaf,所以这里重点讲解服务层的测试。

1 bootstrap.php文件

如下,我们通过这样的类似入口文件的代码,初始化yaf框架,实现对服务层的调用。

<?php
ini_set('error_reporting', E_ALL); // or error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');


define("BASE_PATH", __DIR__ . "/../");
define("APP_PATH", BASE_PATH . "application/");
define("ENV", get_cfg_var('SERVER_ENV'));

include BASE_PATH . 'vendor/autoload.php';

/**
 * Class TestBase
 * 说明:这里我们用了autoload.php,所以YAF的php.ini需设置:yaf.use_spl_autoload=1,
 * 否则会报错:Warning: Yaf_Loader::autoload(): Failed opening script ... No such file or directory
 */

static $application = null;

// 必须实例化Yaf_Application Final类;
// 载入Application必备的配置文件;
// Yaf_Application代表的是一个产品/项目,必须保证单例。
$application = Yaf_Registry::get('Application');
if (!$application) {
    $application = new Yaf_Application(BASE_PATH . "configs/application.ini", ENV);
    $application->bootstrap();

    Yaf_Registry::set('Application', $application);
}

2 phpunit.xml文件

在phpunit.xml中,我们指定启动文件,配置测试目录和文件后缀:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit stderr="true" bootstrap="tests/bootstrap.php" backupGlobals="false">
    <testsuites>
        <testsuite name="API Test Suite">
            <directory suffix=".php">./tests/api/</directory>
        </testsuite>
    </testsuites>
 </phpunit>

这样我们在tests/下的测试用例都可以直接调用yaf的组件,以及所有的library下的类了。

3 开始测试

./vendor/phpunit/phpunit/phpunit

1 条评论

小旭 says: 回复

http://47.128.204.47/2717.html
您好,能否百忙之中指导小弟一下,如何tests/下的测试用例直接调用yaf组件吗?能否帮忙写几个示例呢?万分感谢。

回复 小旭 取消回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

昵称 *