温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在PHP中使用phpunit实现单元测试

发布时间:2021-03-23 16:37:32 来源:亿速云 阅读:131 作者:Leah 栏目:开发技术

如何在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.

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI