gpt4 book ai didi

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

转载 作者:qq735679552 更新时间:2022-09-29 22:32:09 25 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章PHP测试框架PHPUnit组织测试操作示例由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

本文实例讲述了PHP测试框架PHPUnit组织测试操作。分享给大家供大家参考,具体如下:

首先是目录结构 。

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

源文件夹为 src/ 测试文件夹为 tests/ 。

User.php 。

<?phpclass 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 。

<?phpuse 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 。

<?phpfunction __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测试框架PHPUnit组织测试操作示例的文章就讲到这里了,如果你想了解更多关于PHP测试框架PHPUnit组织测试操作示例的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com