1. 程式人生 > >PHPUnit安裝及入門(Unix或者Linux下)

PHPUnit安裝及入門(Unix或者Linux下)

        系統分析與設計的課程大Project做完了,但是作為一個系統的軟體流程,怎麼能少了軟體測試,有了軟測,才是真正的軟體工程。由於我們的課程專案使用的是php寫的後臺。而PHPUnit是一個非常好的php單元測試的工具。

       首先,要來安裝phpunit,在linux或者unix下,先到官網下載 https://phpunit.de/

       下載下來後,命令列進入當前目錄,執行如下的命令:


        看到這個基本就說明安裝成功了。

        接下來,我們可以進行測試了。

例 1: 用 PHPUnit 測試陣列操作

<?php
class StackTest extends PHPUnit_Framework_TestCase
{
    public function testPushAndPop()
    {
        $stack = array();
        $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));
    }
}
?>
然後在命令列執行如下所示:


例 2: 用 @depends 標註來表達依賴關係

<?php
class StackTest extends PHPUnit_Framework_TestCase
{
    public function testEmpty()
    {
        $stack = array();
        $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);

        return $stack;
    }

    /**
     * @depends testPush
     */
    public function testPop(array $stack)
    {
        $this->assertEquals('foo', array_pop($stack));
        $this->assertEmpty($stack);
    }
}
?>
然後在命令列執行如下所示:


例 3: 利用測試之間的依賴關係

<?php
class DependencyFailureTest extends PHPUnit_Framework_TestCase
{
    public function testOne()
    {
        $this->assertTrue(FALSE);
    }

    /**
     * @depends testOne
     */
    public function testTwo()
    {
    }
}
?>

命令後執行結果如下所示:
phpunit --verbose DependencyFailureTest
PHPUnit 4.7.0 by Sebastian Bergmann and contributors. FS Time: 0 seconds, Memory: 5.00Mb There was 1 failure: 1) DependencyFailureTest::testOne Failed asserting that false is true. /home/sb/DependencyFailureTest.php:6 There was 1 skipped test: 1) DependencyFailureTest::testTwo This test depends on "DependencyFailureTest::testOne" to pass. FAILURES! Tests: 1, Assertions: 1, Failures: 1, Skipped: 1.