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'); //失败
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值