2012-11-08 12 views
10

consideri una funzione che fa un po 'di gestione delle eccezioni sulla base degli argomenti passati:Come si annullano le eccezioni in Dart?

List range(start, stop) { 
    if (start >= stop) { 
     throw new ArgumentError("start must be less than stop"); 
    } 
    // remainder of function 
} 

Come faccio a testare che il giusto tipo di eccezione è sollevata?

risposta

23

In questo caso, esistono diversi modi per verificare l'eccezione. Per testare semplicemente che un'eccezione viene sollevata:

expect(() => range(5, 5), throws); 

Per verificare che il tipo giusto di eccezione viene sollevata:

expect(() => range(5, 2), throwsA(new isInstanceOf<ArgumentError>())); 

per garantire che nessuna eccezione è sollevata:

expect(() => range(5, 10), returnsNormally); 

a prova il tipo di eccezione e il messaggio di eccezione:

expect(() => range(5, 3), 
    throwsA(predicate((e) => e is ArgumentError && e.message == 'start must be less than stop'))); 

qui è un altro modo per farlo:

expect(() => range(5, 3), 
    throwsA(allOf(isArgumentError, predicate((e) => e.message == 'start must be less than stop')))); 

(Grazie a Graham Wheeler a Google per gli ultimi 2 soluzioni).

+0

stavo facendo 'aspettano (gamma (5, 3), throwsArgumentError) ', ma l'eccezione non è stata inclusa nell'aspettativa. Il primo argomento da aspettarsi deve essere una funzione anonima che alla fine verrà lanciata quando chiamata. La tua risposta mi ha aiutato a trovare questo stupido errore, grazie! – fgiraldeau

2

Mi piace questo approccio:

test('when start > stop',() { 
    try { 
    range(5, 3); 
    } on ArgumentError catch(e) { 
    expect(e.message, 'start must be less than stop'); 
    return; 
    } 
    throw new ExpectException("Expected ArgumentError"); 
}); 
+0

È un po 'più prolisso delle altre opzioni, ma è abbastanza leggibile e non presuppone che tu abbia memorizzato l'intera libreria unittest;) –

1

Per il semplice test eccezione, io preferisco usare il metodo API statica:

Expect.throws(
    // test condition 
(){ 
    throw new Exception('code I expect to throw'); 
    }, 
    // exception object inspection 
    (err) => err is Exception 
);