19

私がテストしているメソッドが PHP のE_NOTICE"undefined index : foo" という結果になった場合に失敗する simpleTest を使用したテストを書きたいと思います。

私は試してみましたが、成功しませんでしたexpectError()expectException()simpleTest Web ページは、simpleTest がコンパイル時の PHP エラーをキャッチできないことを示していますE_NOTICEが、実行時エラーのようです。

そのようなエラーをキャッチして、その場合にテストを失敗させる方法はありますか?

4

4 に答える 4

21

それは本当に簡単ではありませんでしたが、最終的に必要なE_NOTICEエラーをキャッチすることができました. ステートメントerror_handlerでキャッチする例外をスローするには、現在をオーバーライドする必要がありました。try{}

function testGotUndefinedIndex() {
    // Overriding the error handler
    function errorHandlerCatchUndefinedIndex($errno, $errstr, $errfile, $errline ) {
        // We are only interested in one kind of error
        if ($errstr=='Undefined index: bar') {
            //We throw an exception that will be catched in the test
            throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
        }
        return false;
    }
    set_error_handler("errorHandlerCatchUndefinedIndex");

    try {
        // triggering the error
        $foo = array();
        echo $foo['bar'];
    } catch (ErrorException $e) {
        // Very important : restoring the previous error handler
        restore_error_handler();
        // Manually asserting that the test fails
        $this->fail();
        return;
    }

    // Very important : restoring the previous error handler
    restore_error_handler();
    // Manually asserting that the test succeed
    $this->pass();
}

これは、例外をキャッチするためだけに例外をスローするようにエラーハンドラーを再宣言する必要があるため、少し複雑すぎるようです。もう 1 つの難しい部分は、例外がキャッチされたときとエラーが発生しなかったときの両方で error_handler を正しく復元することでした。

于 2010-07-16T04:11:42.040 に答える
6

通知エラーをキャッチする必要はありません。「array_key_exists」の結果をテストしてから、そこから続行することもできます。

http://www.php.net/manual/en/function.array-key-exists.php

false をテストし、失敗させます。

于 2013-04-19T18:27:51.810 に答える