一、獲取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'); //失敗