首页 > 编程 > PHP > 正文

PHP使用phpunit进行单元测试示例

2019-11-21 19:50:56
字体:
来源:转载
供稿:网友

本文实例讲述了PHP使用phpunit进行单元测试。分享给大家供大家参考,具体如下:

1. linux服务器上安装phpunit

wget https://phar.phpunit.de/phpunit.pharchmod +x phpunit.pharsudo mv phpunit.phar /usr/local/bin/phpunit

建立phpunit短命令

phpunit --version

[root@dongzi phpunit_test]# phpunit --versionPHPUnit 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.phpPHPUnit 5.6.1 by Sebastian Bergmann and contributors..F                                 2 / 2 (100%)Time: 82 ms, Memory: 6.75MBThere was 1 failure:1) UnitTest::indexEqualsFailed asserting that 1 matches expected 2./wwwroot/phpunit_test/UnitTest.php:18FAILURES!Tests: 2, Assertions: 3, Failures: 1.

结果显示测试php文件中共运行两个模块,有一个模块错误

错误测试方法名为indexEquals报错行为18行。

因为因为stack等于0不等于断言的1,所以报错,定位错误成功。

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

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表