PHPUnit (1) 安裝

Installation

For a system-wide installation via Composer, you can run:

1
$ composer global require "phpunit/phpunit=5.5.*"

In MacOS Sierra, you might need to use sudo for permission issue.

After installation, you can check PHPUnit version by:

1
2
$ phpunit --version
PHPUnit 5.5.7 by Sebastian Bergmann and contributors.

If it shows up command not found, try:

1
2
3
4
5
6
7
$ ~/.composer/vendor/bin/phpunit --version
PHPUnit 5.5.7 by Sebastian Bergmann and contributors.

# Then you can use alias for short
$ alias phpunit='~/.composer/vendor/bin/phpunit'
$ phpunit --version
PHPUnit 5.5.7 by Sebastian Bergmann and contributors.

Test PHPUnit

After installation of PHPUnit, let's try use it.

Create TestClass.php

  1. Make a new class TestSample
  2. TestSample inherits from PHPUnit\Framework\TestCase.
  3. Call method assertEquals for this test.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
use PHPUnit\Framework\TestCase;

class TestSample extends TestCase
{

function testSample1()
{

// assertEquals($a, $b) checks if $a == $b.
$this->assertEquals(2, 1+1);
}

function testSample2()
{

$this->assertEquals(2, 1-1);
}
}

Running Test

Save php file, in terminal we can run it by command. Option --color can make syntax highlighting.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$ phpunit --color TestSample.php
PHPUnit 4.7.3 by Sebastian Bergmann and contributors.

.F

Time: 81 ms, Memory: 18.00Mb

There was 1 failure:

1) TestSample::testSample2
Failed asserting that 0 matches expected 2.

/tmp/TestSample.php:10

FAILURES!
Tests: 2, Assertions: 2, Failures: 1.

Explaination of Result

Line #4 ".F" tells you the overall results charactor by charactor.

Mark Result
. Pass
F Fail

Full details at here.

References

  1. PHPUnit Official Documentation
  2. PHPの単体テストを自動化したかったので、phpunitを試してみた。
分享到 評論