Domanda

Vorrei scrivere un test usando Sempletsty che avrebbe fallito se il metodo che sto testando risultati in un E_NOTICE PHP "indefinito indice: foo".

Ho provato expectError() e expectException() senza successo.La pagina Web semplificata indica che SimpleTest non è in grado di catturare gli errori PHP del tempo di compilazione, ma E_NOTICE sembra essere un errore di esecuzione.

C'è un modo per catturare un simile errore e rende il mio test fallire se è così?

È stato utile?

Soluzione

Non è stato davvero facile, ma finalmente sono riuscito a prendere l'errore E_NOTICE che volevo.Avevo bisogno di sovrascrivere l'attuale error_handler per lanciare un'eccezione che catturerò in un'istruzione 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();
}
.

Questo sembra un po 'eccessivamente complicato di dover ridecellare il gestore di errore per lanciare un'eccezione solo per prenderlo.L'altra parte difficile stava ripristinando correttamente l'errore_handler entrambi quando un'eccezione è stata catturata e non si è verificato alcun errore, altrimenti si incasina solo con la gestione degli errori semplici.

Altri suggerimenti

Non c'è davvero bisogno di prendere l'errore di preavviso.Si potrebbe anche testare il risultato di "array_key_exists" e poi procedere da lì.

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

Test per false e fallisce.

Non lo prenderai mai all'interno del blocco try-catch, fortunatamente abbiamo set_error_handler ():

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

Puoi fare qualsiasi cosa tu voglia all'interno della funzione my_handle () o lasciarlo vuoto per silenziare l'avviso, anche se, non è raccomandato.Un normale gestore dovrebbe essere così:

function myErrorHandler($errno, $errstr, $errfile, $errline)
.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top