simpleTest에서 "정의되지 않은 인덱스" E_NOTICE 오류를 잡는 방법은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/3261051

  •  16-09-2020
  •  | 
  •  

문제

테스트 중인 메서드가 PHP에서 결과를 나타내는 경우 실패할 simpleTest를 사용하여 테스트를 작성하고 싶습니다. E_NOTICE "정의되지 않은 인덱스:푸".

나는 노력했다 expectError() 그리고 expectException() 성공없이.simpleTest 웹페이지에는 simpleTest가 컴파일 시간 PHP 오류를 포착할 수 없다고 나와 있지만, E_NOTICE 런타임 오류인 것 같습니다.

그러한 오류를 포착하여 테스트가 실패하게 만드는 방법이 있습니까?

도움이 되었습니까?

해결책

정말 쉽지는 않았지만 마침내 그 일을 잡을 수 있었습니다. 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();
}

이는 단지 예외를 잡기 위해 오류 처리기를 다시 선언해야 하는 다소 지나치게 복잡한 것 같습니다.다른 어려운 부분은 예외가 포착되고 오류가 발생하지 않은 경우 error_handler를 올바르게 복원하는 것이었습니다. 그렇지 않으면 SimpleTest 오류 처리가 엉망이 됩니다.

다른 팁

실제로 알림 오류를 잡을 필요는 없습니다.'array_key_exists'의 결과를 테스트한 다음 거기서부터 진행할 수도 있습니다.

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

거짓인지 테스트하고 실패하게 만드세요.

try-catch 블록 내에서는 절대로 이를 잡을 수 없습니다. 다행히도 set_error_handler()가 있습니다.

<?php
function my_handle(){}
set_error_handler("my_handle");
echo $foo["bar"];
?>

my_handle() 함수 내에서 원하는 모든 작업을 수행할 수 있으며, 알림을 무음으로 설정하려면 비워 둘 수도 있지만 권장되지는 않습니다.일반 핸들러는 다음과 같아야 합니다:

function myErrorHandler($errno, $errstr, $errfile, $errline)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top