Skip to content

Zeroplex 生活隨筆

軟體開發、伺服器和生活瑣事

小 縮小字型大小。 中 重設字型大小。 大 放大字型大小。

PHP Notice in testing by PHPUnit

Posted on 2016 年 6 月 10 日2021 年 3 月 12 日 By 日落 在〈PHP Notice in testing by PHPUnit〉中尚無留言

這邊先做個錯誤示範,以下的程式執行時,會因為對一個不存在的 array index 取值:

class Worker
{
    public function work()
    {
        $arr = [];

        $elem = $arr['nonExist'];
    }
}

執行時會出現以下錯誤訊息:

PHP Notice:  Undefined index: nonExist in /home/zero/tmp/phpunit/Worker.php

PHPUnit 執行 unit test 時會自動將 notice / warning 都轉成 exception,使用者變可以透過「@expectedException」來檢查確認是否有發生預期的錯誤:

class WorkerTest extends PHPUnit_Framework_TestCase
{
    /**
     * @expectedException PHPUnit_Framework_Error_Notice
     */
    public function testWorker()
    {
        $worker = new Worker();
        $worker->work();
    }
}

unit test 執行結果:

zero@zero-lab:~/tmp/tests$ ./phpunit 
PHPUnit 5.5-gc2e4cf1 by Sebastian Bergmann and contributors.

.                                                                   1 / 1 (100%)

Time: 202 ms, Memory: 3.00MB


但是當 array 取值前後加上了 try … catch 時會發生什麼事呢?

class Worker
{
    public function work()
    {
        try {
            $arr = [];

            $elem = $arr['nonExist'];
        } catch (Exception $e) {
            // do something
        }
    }
}

再來執行一次 unit test:

zero@zero-lab:~/tmp/tests$ ./phpunit 
PHPUnit 5.5-gc2e4cf1 by Sebastian Bergmann and contributors.

F                                                                   1 / 1 (100%)

Time: 27 ms, Memory: 3.00MB

There was 1 failure:

1) WorkerTest::testWorker
Failed asserting that exception of type "PHPUnit_Framework_Error_Notice" is thrown.

phpunit 顯示錯誤訊息,原本預期會收到「PHPUnit_Framework_Error_Notice」但現在確沒有收到,造成 assertion failed。

這時若在 catch 中將「$e」dump 出來,會發現 PHPUnit_Framework_Error_Notice 被程式中的 try … catch 抓到了:

object(PHPUnit_Framework_Error_Notice)#20 (8) {
  ....
}

個人覺得這個行為不是非常直覺,在正常行況下,PHP notice 不會被 try … catch 抓到,而會正常執行下去,但當執行測試時,卻會因為 phpunit 將 notice / warning 自動轉成 exceptions 而導致程式的 work flow 與原先的設計不同,並造成測試時的警報。

目前還沒有想到什麼方法可以避開這個問題,若真要解決這個問題的話,最好的辦法,應該還是在實作時就避免出現 PHP notice 或 warning。

Tags:PHP, PHPUnit

文章導覽

Previous Post: 不需要 PHP eval() 即可執行使用者自訂動作的寫法
Next Post: 在 gnome-teminal 使用 Ctrl + arrow 切換 GNU screen 視窗

發佈留言 取消回覆

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *


其他

關於我  (About me)

小額贊助

  文章 RSS Feed

  留言 RSS Feed

Apache AWS Bash C/C++ Docker FreeBSD GCP Git Google Java JavaScript Laravel Linux Microsoft MSSQL MySQL Nginx PHP PHPUnit PostgreSQL Python Qt Ubuntu Unix Vim Web Windows WordPress XD 作業系統 分享 好站推薦 專題 攝影 新奇搞笑 新聞 旅遊 生活雜記 程式設計 網路架站 網頁設計 資訊學習 資訊安全 遊戲 音樂


創用 CC 授權條款
本著作係採用創用 CC 姓名標示-相同方式分享 4.0 國際 授權條款授權.