2010-11-21 12 views
7

Sto utilizzando ScalaTest per testare qualche codice Scala. Io attualmente testando per le eccezioni previste con codice come questoCome testare le proprietà aggiuntive delle eccezioni attese utilizzando ScalaTest

import org.scalatest._ 
import org.scalatest.matchers.ShouldMatchers 

class ImageComparisonTest extends FeatureSpec with ShouldMatchers{ 

    feature("A test can throw an exception") { 

     scenario("when an exception is throw this is expected"){ 
      evaluating { throw new Exception("message") } should produce [Exception] 
     } 
    } 
} 

Ma vorrei aggiungere ulteriore controllo sul l'eccezione, per esempio Vorrei verificare che il messaggio di eccezione contenga una determinata stringa.

C'è un modo "pulito" per farlo? O devo usare un blocco catch try?

risposta

16

ho trovato una soluzione

val exception = intercept[SomeException]{ ... code that throws SomeException ... } 
// you can add more assertions based on exception here 
9

È possibile fare la stessa cosa con la valutazione ... dovrebbe produrre la sintassi, perché intercetta come, restituisce l'eccezione catturato:

val exception = 
    evaluating { throw new Exception("message") } should produce [Exception] 

Quindi ispezionare l'eccezione.

+0

Funziona e mi piace t la sua sintassi: è in linea con tutti i "dovrebbe essere" per i risultati delle funzioni. –

+0

'evaluationing' è deprecato in 2.x e rimosso in 3.x. I documenti di deprecazione consigliano di usare 'an [Exception] should be throw but 'invece. Comunque 3.0.0-M14 restituisce un 'Assertion':' val ex: Assertion = an [Exception] dovrebbe essere gettatoBy {lanciare una nuova Exception ("boom")} '. C'è un modo per recuperare l'eccezione lanciata? – kostja

2

Se è necessario esaminare ulteriormente un'eccezione previsto, è possibile catturare utilizzando la seguente sintassi:

val thrown = the [SomeException] thrownBy { /* Code that throws SomeException */ } 

Questa espressione restituisce l'eccezione catturato in modo da poter esaminare ulteriormente:

thrown.getMessage should equal ("Some message") 

puoi anche catturare e controllare un'eccezione prevista in una dichiarazione, come questa:

the [SomeException] thrownBy { 
    // Code that throws SomeException 
} should have message "Some message"