如何在simpleTest中捕获"未定义的索引"E_NOTICE错误?

pix*_*tic 16 php simpletest exception

我想使用simpleTest编写测试,如果我正在测试的方法导致PHP E_NOTICE"未定义的索引:foo" ,则会失败.

我试图expectError()expectException()没有成功.simpleTest网页表明simpleTest无法捕获编译时PHP错误,但E_NOTICE似乎是运行时错误.

有没有办法捕获这样的错误,如果是这样我的测试失败?

pix*_*tic 17

这并不容易,但我终于设法抓住了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();
}
Run Code Online (Sandbox Code Playgroud)

这似乎有点过于复杂,不得不重新声明错误处理程序以抛出异常只是为了捕获它.另一个困难的部分是在捕获异常并且没有发生错误时正确地恢复error_handler,否则它只是混乱了SimpleTest错误处理.

  • 这语言有多糟糕! (6认同)

Rob*_*ita 5

确实没有必要抓住通知错误.还可以测试'array_key_exists'的结果,然后从那里继续.

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

测试是否错误并使其失败.

  • 有一种情况是将数组投影到另一个数组中.您不希望测试每个单独的映射,您希望捕获任何一个映射失败的情况.除了例外,这将更容易. (4认同)