PHPunit快速入门

一、获取PHPunit
要获取 PHPUnit,最简单的方法是下载 PHPUnit 的 PHP 档案包 (PHAR),它将 PHPUnit 所需要的所有必要组件(以及某些可选组件)捆绑在单个文件中:

要使用 PHP档案包(PHAR)需要有 phar 扩展。

全局安装 PHAR

$ wget https://phar.phpunit.de/phpunit.phar
$ chmod +x phpunit.phar
$ sudo mv phpunit.phar /usr/local/bin/phpunit
$ phpunit --version
PHPUnit x.y.z by Sebastian Bergmann and contributors.

也可以直接使用下载的 PHAR 文件:

$ wget https://phar.phpunit.de/phpunit.phar
$ php phpunit.phar --version
PHPUnit x.y.z by Sebastian Bergmann and contributors.

二、编写PHPunit测试用例
新建一个 test.php:

vi test.php

1
写入以下代码:

<?php
use PHPUnit\Framework\TestCase;

class Test extends TestCase
{
    #也可以直接继承PHPUnit_Framework_TestCase,从而不需要写use语句

    public function testPushAndPop()
    {
        $stack = [];
        $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));
    }
}
?>

保存后使用命令进行测试:

# phpunit test.php

1
结果如下:

PHPUnit 5.7.4 by Sebastian Bergmann and contributors.

Runtime:       PHP 7.1.0

.                                           1 / 1 (100%)

Time: 187 ms, Memory: 8.00MB

OK (1 test, 5 assertions)

phpunit提供了大量的assert函数,详细看 abstract class PHPUnit_Framework_Assert 。
例如:

public static function assertTrue($condition, $message = '')

public static function assertSame($expected, $actual, $message = '')

public static function assertEquals($expected, $actual, $message = '', $delta = 0, $maxDepth = 10, $canonicalize = FALSE, $ignoreCase = FALSE)

public static function assertArrayHasKey($key, array $array, $message = '')

使用方法:

this->assertTrue($a, "a error:$a);

this->assertTrue($a=='xy', "a($a) != xy);

this->assertSame('xy', $a, "a error");

this->assertEquals('xy', $a, "a error");

this->assertArrayHasKey('uid', $arr);

$message参数是在assert失败的情况下输出。

assertSame 成立的条件必需类型于值都相等才成立,而assertEquals不是。
如:

$this->assertEquals(2, '2'); //通过

$this->assertSame(2, '2'); //失败
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章