加入收藏 | 设为首页 | 会员中心 | 我要投稿 云计算网_泰州站长网 (http://www.0523zz.com/)- 视觉智能、AI应用、CDN、行业物联网、智能数字人!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP使用phpunit开展单元测试示例

发布时间:2022-06-27 01:07:17 所属栏目:PHP教程 来源:互联网
导读:本文实例讲述了PHP使用phpunit进行单元测试,分享给大家供大家参考,具体如下: 1. linux服务器上安装phpunit wget https://phar.phpunit.de/phpunit.phar chmod +x phpunit.phar sudo mv phpunit.phar /usr/local/bin/phpunit 建立phpunit短命令 phpunit
  本文实例讲述了PHP使用phpunit进行单元测试,分享给大家供大家参考,具体如下:
 
  1. linux服务器上安装phpunit
 
  wget https://phar.phpunit.de/phpunit.phar
 
  chmod +x phpunit.phar
 
  sudo mv phpunit.phar /usr/local/bin/phpunit
 
  建立phpunit短命令
 
  phpunit --version
 
  [root@dongzi phpunit_test]# phpunit --version
 
  PHPUnit 5.6.1 by Sebastian Bergmann and contributors.
 
  2. 创建单元测试文件
 
  文件名称为UnitTest.php
 
  我们可以在单元测试文件内的方法里面调用功能模块,用数据模拟看是否运行正常,如果通则会报错,断掉。
 
  <?php
    class UnitTest extends PHPUnit_Framework_TestCase{
      public function testPushAndPop(){
        $stack = array();
        $this->assertEquals(0,count($stack));
        array_push($stack,'foo');
        //断言插入数据到$stack数组后值是否等于1
        $this->assertEquals(1,count($stack));
      }
      /**
       *定义test标签声明该方法是测试方法
       *@test
       ***/
      public function indexEquals(){
        $stack = array(1,2,3,4);
        //断言$stack[0]等于2
        $this->assertEquals(2,$stack[0]);
      }
    }
  ?>
  3. phpunit运行文件
 
  [root@dongzi phpunit_test]# phpunit UnitTest.php
  PHPUnit 5.6.1 by Sebastian Bergmann and contributors.
  .F                                 2 / 2 (100%)
  Time: 82 ms, Memory: 6.75MB
  There was 1 failure:
  1) UnitTest::indexEquals
  Failed asserting that 1 matches expected 2.
  /wwwroot/phpunit_test/UnitTest.php:18
  FAILURES!
  Tests: 2, Assertions: 3, Failures: 1.
  结果显示测试php文件中共运行两个模块,有一个模块错误
 
  错误测试方法名为indexEquals报错行为18行。
 
  因为因为stack等于0不等于断言的1,所以报错,定位错误成功。
 
 

(编辑:云计算网_泰州站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读