Home >Backend Development >PHP Tutorial >PHPUnit安装及使用示例_PHP

PHPUnit安装及使用示例_PHP

WBOY
WBOYOriginal
2016-05-31 19:28:30894browse

PHPUnit是zend官方大力支持的测试框架,高质量的单元测试时保证项目质量的基础,能够有效的减少BUG,改善程序。

安装PHPUnit:

在php的目录下:

代码如下:


pear channel-discover pear;
pear install phpunit/PHPUnit

windows下将php的环境变量加入到PATH环境变量中。
简单使用:

代码如下:


class StackTest extends PHPUnit_Framework_TestCase
{
 
    public function testArray()
    {
        $stack = array();
        $this->assertEquals(0, count($stack));
 
        array_push($stack, 'foo');
        $this->assertEquals('foo', $stack[count($stack)-1]);
        $this->assertEquals(1, count($stack));
 
        $this->assertEquals('foo', array_pop($stack));
        $this->assertEquals(0, count($stack));
    }
   
    /**
     * @test
     */
    public function Stringlen()
    {
        $str = 'abc';
        $this->assertEquals(3,  strlen($str));
    }
}

从上可以看到编写PHPUnit的基本规律:
(1)类Class的测试写在ClassTest中
(2)ClassTest继承PHPUnit_Framework_TestCase
(3)测试方法都是test*格式,也可以通过@test将其标注为测试方法。
(4)通过断言方法assertEquals来对实际值和预期值进行断言。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn