服务器之家

服务器之家 > 正文

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

时间:2021-08-20 14:36     来源/作者:巴八灵

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

1. linux服务器上安装phpunit

?
1
2
3
wget https://phar.phpunit.de/phpunit.phar
chmod +x phpunit.phar
sudo mv phpunit.phar /usr/local/bin/phpunit

建立phpunit短命令

phpunit --version

?
1
2
[root@dongzi phpunit_test]# phpunit --version
PHPUnit 5.6.1 by Sebastian Bergmann and contributors.

2. 创建单元测试文件

文件名称为UnitTest.php

我们可以在单元测试文件内的方法里面调用功能模块,用数据模拟看是否运行正常,如果通则会报错,断掉

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?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运行文件

?
1
2
3
4
5
6
7
8
9
10
[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,所以报错,定位错误成功。

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

原文链接:https://www.cnblogs.com/lisqiong/p/5964375.html

标签:

相关文章

热门资讯

yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
2021年耽改剧名单 2021要播出的59部耽改剧列表
2021年耽改剧名单 2021要播出的59部耽改剧列表 2021-03-05
返回顶部