PHP测试框架PHPUnit组织测试操作示例

yipeiwu_com5年前PHP代码库

本文实例讲述了PHP测试框架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

更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP错误与异常处理方法总结》、《php字符串(string)用法总结》、《PHP数组(Array)操作技巧大全》、《PHP运算与运算符用法总结》、《PHP网络编程技巧总结》、《PHP基本语法入门教程》、《php面向对象程序设计入门教程》及《php优秀开发框架总结

希望本文所述对大家PHP程序设计有所帮助。

相关文章

php解析html类库simple_html_dom(详细介绍)

下载地址:https://github.com/samacs/simple_html_dom解析器不仅仅只是帮助我们验证html文档;更能解析不符合W3C标准的html文档。它使用了类似...

php class中self,parent,this的区别以及实例介绍

一,this 1,要用this,你必有是一个对像的形势,不然它会报错的,Fatal error: Using $this when not in object context。2,th...

PHP基于socket实现客户端和服务端通讯功能

本文主要介绍了PHP基于socket实现的简单客户端和服务端通讯功能,可实现服务端接收客户端发送的字符串进行翻转操作后返回客户端的功能,需要的朋友可以参考下 服务端: <...

php mssql 分页SQL语句优化 持续影响

复制代码 代码如下:<?php /** * @Filename :page.sql.class.php * @CreatTime :2009-01-06 * @Descrition...

执行、获取远程代码返回:file_get_contents 超时处理的问题详解

天气终于晴了,但问题来了。在实现两个站点间用户数据同步,当使用php函数 file_get_contents抓取执行远程页面时,如果连接超时将会输出一个Fatal Error或相当的慢,...