Skip to content

Instantly share code, notes, and snippets.

@mag5323
Created November 30, 2016 10:13
Show Gist options
  • Save mag5323/1781f7b3bb3b243d45205e28c4a10a15 to your computer and use it in GitHub Desktop.
Save mag5323/1781f7b3bb3b243d45205e28c4a10a15 to your computer and use it in GitHub Desktop.
A guide of PHPUnit

測試

  1. test class 要繼承 PHPUnit_Framework_TestCase e.g. class CartTest extends PHPUnit_Framework_TestCase {}

  2. PHPUnit 會將 test 開頭的方法視為測試方法 e.g. public function testEmpty() {}

    或者也可以在 docblock 中標註 @test, 範例如下

    /**
     * @test
     */
    public function empty(){
        $stack = [];
        $this->assertEquals(0, count($stack));
    }
  3. 斷言的寫法為 $this->assertEquals(預期結果, 測試對象), 可見範例如上

相依性

  • 在 docBlock 中用 @depends 標記相依性
    public function testEmpty()
    {
        $stack = [];
        $this->assertEmpty($stack);
        return $stack;
    }
    
    /**
     * @depends testEmpty
     */
    public function testPush(array $stack)
    {
        array_push($stack, 'foo');
        $this->assertEquals('foo', $stack[count($stack)-1]);
        $this->assertNotEmpty($stack);
    }

DataProviders

  • 在 docBlock 中用 @dataProvider 提供資料的方法 標示資料來源

    /**
     * @dataProvider additionProvider
     */
    public function testAdd($a, $b, $expected)
    {
        $this->assertEquals($expected, $a + $b);
    }
    
    public function additionProvider()
    {
        return [
            [0, 0, 0],
            [0, 1, 1],
            [1, 0, 1],
            [1, 1, 3]
        ];
    }

    也可以為來源資料命名,方便 debug

    return [
        'adding zeros'  => [0, 0, 0],
        'zero plus one' => [0, 1, 1],
        'one plus zero' => [1, 0, 1],
        'one plus one'  => [1, 1, 3]
    ];

   執行測試會顯示錯誤訊息如下 1) DataTest::testAdd with data set "one plus one" (1, 1, 3) Failed asserting that 2 matches expected 3.

Testing exception

  • 在 docBlock 中用 @expectedException 例外名稱 標示這個測試會產生例外, 也可以在程式中使用 $this->setExpectedException(例外名稱) 達到一樣的效果

Testing PHP errors

  • 可以用 @expectedException PHPUnit_Framework_Error 處理 PHP 的錯誤訊息

@group

  • 在 docBlock 中用 @group 指定群組, 執行 phpunit 時加入 --group 群組 即可指定要測試的群組, 也可用 --exclude-group 排除群組

Fixtures

  • 可利用 setUp/tearDown 方法初始化/刪除欲測試的物件, Phpunit 會在各個測試開始執行 setUp, 結束後執行 tearDown

phpunit.xml

  • 執行測試時, 加入 -c or -configuration + yourphpunit.xml, 就可以採用 yourphpunit.xml 做為測試的設定檔

Code coverage

  • 執行 phpunit --coverage-html ./report tests, 即可針對 tests 目錄下的所有檔案進行測試, 並將 code coverage 結果存到 ./report

    P.S. 做到這邊出現 Error: No whitelist configured, no code coverage will be generated

    查了資料 發現 phpunit.xml 內一定要指定 whitelist 才能跑 code coverage

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment