2016-01-02 75 views
7

Voglio testare un metodo di esempio con hint di tipo scalare e tipi rigorosi in PHP7. Quando non passo un argomento, il metodo dovrebbe lanciare un TypeError. PHPSpec tornare errore fatale:PHPSpec Catching TypeError in PHP7

Uncaught TypeError: Argument 1 passed to Example::test

<?php 

class Example 
{ 
    public function test(string $name) 
    { 
     $this->name = $name; 
    } 
} 


class ExampleSpec extends ObjectBehavior 
{ 
    function it_is_initializable() 
    { 
     $this->shouldHaveType('Test\Example'); 
    } 

    function it_check_test_method_when_not_pass_argument() 
    { 
     $this->shouldThrow('\TypeError')->during('test'); 
    } 
} 

All'inizio dichiaro: declare(strict_types=1);

Cosa c'è di sbagliato? Come posso testare il lancio di TypeError?

+0

Quindi l'eccezione viene lanciata ma non catturata? O non viene lanciato e dovrebbe essere? – Will

+0

Metodo di lancio TypeError e I want catch TypeError. Voglio usare $ this-> shouldThrow ('\ TypeError') -> durante ('test'). Questo metodo in PHPSpec funziona quando il metodo restituisce Exception ma non TypeError. – Matrix12

+0

Stai utilizzando la versione più recente di PHPSpec? – Will

risposta

3

Per me funziona se annotare il test di unità con questo:

/** 
* @expectedException \TypeError 
*/ 

Poi la mia prova è verde.

5

In seguito a ulteriori indagini, si tratta di un errore PHPSpec ed è stato segnalato here. Il bug non è stato corretto in diversi mesi, quindi suggerirei di commentarlo.

Se si guarda il codice in src/PhpSpec/Matcher/ThrowMatcher.php, è possibile vedere che PHPSpec recupera le eccezioni che ereditano 'Exception' e quindi controlla il tipo di istanza di tale eccezione. Ma, TypeError non eredita da Exception, eredita da Error. L'unica cosa che ha in comune con un Exception, è che entrambi implementano l'interfaccia Throwable.

Ad esempio:

101  public function verifyPositive($callable, array $arguments, $exception = null) 
102  { 
103   try { 
104    call_user_func_array($callable, $arguments); 
105   } catch (\Exception $e) { 
106    if (null === $exception) { 
107     return; 
108    } 
109 
110    if (!$e instanceof $exception) { 
111     throw new FailureException(sprintf(
112      'Expected exception of class %s, but got %s.', 
113      $this->presenter->presentValue($exception), 
114      $this->presenter->presentValue($e) 
115    )); 
116    } 

relazione il bug, spiegare questi dettagli, e mostrare loro this documentation circa l'eredità di TypeError.

+1

Ho segnalato quell'errore. Non so quando questo bug verrà corretto. – Matrix12

+0

@ Matrix12 È possibile rilevare (Errore $ e) per rilevare errori ... o qualsiasi classe specifica che interfacce Throwable –