PHPunit quick start

1. Obtaining PHPunit
To obtain PHPUnit, the easiest way is to download the PHP Archive (PHAR) of PHPUnit, which bundles all the necessary components (and some optional components) required by PHPUnit in a single file:

To use the PHP archive (PHAR), the phar extension is required.

Install PHAR globally

$ 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.

You can also use the downloaded PHAR file directly:

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

2. Writing PHPunit test cases
Create a new test.php:

vi test.php

1
write the following code:

<?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));
    }
}
?>

Use the command to test after saving:

# phpunit test.php

1 The
results are as follows:

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 provides a large number of assert functions, see abstract class PHPUnit_Framework_Assert for details.
E.g:

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 = '')

Instructions:

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);

The $message parameter is output if the assert fails.

The condition that assertSame holds must be equal to the type and value, but assertEquals is not.
Such as:

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

$this->assertSame(2, '2'); //失败

Guess you like

Origin blog.csdn.net/qq_26249609/article/details/103202040