在 Laravel 中使用 SimpleTest

在 PHP 中,要做 Unit test,PHPUnit 是主流,但使用 SimpleTest 最大的優點,就是「簡單」,以及可以透過流覽器使用,用格式化和彩色來顯示測試結果,更為清楚明白。

按原開發者的說明,「simple」不是只有「lite」的功能,而是使用上的「simple」。

很高興,在經過快 10 年之後,有人把它修改成可以經由 composer 來安裝,因此,在 Laravel 中,可以更容易的使用 SimpleTest。只要在 composer.json 中加上下面的設定,再執行 composor install 即可。

"require-dev": {
                "simpletest/simpletest": "^1.1"
        },

以下說明,主要是參考 <PHP in Action> 的內容,要更進一步學習 SimpleTest ,可參考該書。

First, let's create a very simple test class to test the function of SimpleTest. This class, app\Tests\TestOfTest.php, is shown as follows.

<?php
namespace App\Tests;
use UnitTestCase;
class TestOfTest extends UnitTestCase 
{
   function testTrial() 
   {
      $flg = false;
      $this->assertEqual($flg, false, 'My first test');
   }
}

Now, create a TestController to invoke the Test Class. This test controller is listed as follows.

<?php
namespace App\Http\Controllers;
use HtmlReporter;
use App\Tests\TestOfTest;
class TestController extends Controller
{
    public function __construct()
    {
        $ip = $_SERVER["REMOTE_ADDR"];
        if ($ip !== '127.0.0.1') {
            die("Cannot run here!");
        }
    }
    public function anyIndex()
    {
        $test = new \App\Tests\TestOfTest();
        $test->run(new \HtmlReporter());
    }
}

Browsing the url http://localhost:8080/test, we can see the result of test failed. Great, the SimpleTest works successfully.

App\Tests\TestOfTest

Fail: testTrial -> Equal expectation fails as [Boolean: true] does not match [Boolean: false] at [/home/ajax/test/laravel-5.0-test/app/Tests/TestOfTest.php line 11]

1/1 test cases complete: 0 passes, 1 fails and 0 exceptions.

Open app\Tests\TestOfTest.php to modify $flg = false; , and then refresh the browser, we can obtain the result of test passed.

App\Tests\TestOfTest

1/1 test cases complete: 1 passes, 0 fails and 0 exceptions.

Quite simple, isn't it?

更進一步,假如要顯示 pass 的測試,參考官網的說明,建立下面的 class

<?php
namespace App\Tests;
use HtmlReporter;
class ShowPasses extends HtmlReporter
{
    function paintPass($message) {
        parent::paintPass($message);
        print "<span class=\"pass\">Pass</span>: ";
        $breadcrumb = $this->getTestList();
        array_shift($breadcrumb);
        print implode("->", $breadcrumb);
        print "->$message<br />\n";
    }
   
    protected function getCss() {
        return parent::getCss() . ' .pass { color: green; }';
    }
}

然後,在 controller 的 action 中,使用 ShowPasses() 來顯示結果。

public function anyIndex()
{
    $test = new \App\Tests\TestOfTest();
    $test->run(new \App\Tests\ShowPasses());
}

顯示結果如下

App\Tests\TestOfTest

Pass: testTrial->My first test at [/var/www/html/ajtest/course/web-src/app/Tests/TestOfTest.php line 12]

1/1 test cases complete: 1 passes, 0 fails and 0 exceptions.