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,所以报错,定位错误成功。

 

posted @ 2016-10-15 14:34  李思琼  阅读(582)  评论(0编辑  收藏  举报