• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

Mark的小试牛刀

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

PHPUnit 组织测试

首先是目录结构

源文件夹为 src/ 

测试文件夹为 tests/

User.php

<?php
class Errorcode
{
    const NAME_IS_NULL = 0;
}

class User
{
    public $name;
    public function __construct($name)
    {
        $this->name=$name;
    }

    public function Isempty()
    {

        try{
            if(empty($this->name))
            {
                throw new Exception('its null',Errorcode::NAME_IS_NULL);
            }
        }catch(Exception $e){
            return $e->getMessage();
        }

        return 'welcome '.$this->name;
    }
}

对应的单元测试文件  UserTest.php

<?php
use PHPUnit\Framework\TestCase;

class UserTest extends TestCase
{
    protected $user;
    public function setUp()
    {
        $this->user = new User('');
    }
    public function testIsempty()
    {
        $this->user->name='mark';
        $result =$this->user->Isempty();
        $this->assertEquals('welcome mark',$result);

        $this->user->name='';
        $results =$this->user->Isempty();
        $this->assertEquals('its null',$results);

    }


}

 

第二个单元测试代码因为要引入 要测试的类  这里可以用 自动载入 避免文件多的话 太多include  

所以在src/ 文件夹里写 autoload.php

<?php

function __autoload($class){
    include $class.'.php';
}

spl_autoload_register('__autoload');

当需要User类时,就去include User.php。写完__autoload()函数之后要用spl_autoload_register()注册上。

 

虽然可以自动载入,但是要执行的命令变得更长了。

打开cmd命令如下

phpunit --bootstrap src/autoload.php tests/UserTest

 

所以我们还可以在根目录写一个配置文件phpunit.xml来为项目指定bootstrap,这样就不用每次都写在命令里了。

phpunit.xml

<phpunit bootstrap="src/autoload.php">
</phpunit>

然后

打开cmd命令 执行MoneyTest 命令如下

phpunit tests/UserTest

打开cmd命令 执行tests下面所有的文件 命令如下  

phpunit tests

  

 

posted on 2017-05-10 17:32  我是天才啊  阅读(1500)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3