2012-11-06 24 views
15

Vorrei scrivere un test per IndexOutOfBoundsException. Tenete presente che siamo tenuti a utilizzare JUnit 3.Java: test delle eccezioni con Junit 3

Il mio codice:

public boolean ajouter(int indice, T element) { 
    if (indice < 0 || indice > (maListe.size() - 1)) { 
     throw new IndexOutOfBoundsException(); 
    } else if (element != null && !maListe.contains(element)) { 
     maListe.set(indice, element); 
     return true; 
    } 
} 

Dopo alcune ricerche, ho scoperto che si può fare questo con JUnit 4 utilizzando @Test(expected = IndexOutOfBoundsException.class) ma non dove ho trovato come fare questo in JUnit 3.

Come posso testare questo utilizzando JUnit 3?

risposta

14

In sostanza, è necessario chiamare il metodo e non riescono, se non lo fa generare l'eccezione destra - o se si getta ogni altra cosa:

try { 
    subject.ajouter(10, "foo"); 
    fail("Expected exception"); 
} catch (IndexOutOfBoundException expect) { 
    // We should get here. You may assert things about the exception, if you want. 
} 
2

Una soluzione semplice è quella di aggiungere un tentativo di cattura per il unittest e lasciare che il test non riuscire quando l'eccezione non viene lanciata

public void testAjouterFail() { 
    try { 
    ajouter(-1,null); 
    JUnit.fail(); 
    catch (IndexOutOfBoundException()) { 
    //success 
    } 
} 
31

testare le eccezioni in JUnit 3 utilizza questo schema:

try { 
    ... code that should throw an exception ... 

    fail("Missing exception"); 
} catch(IndexOutOfBoundsException e) { 
    assertEquals("Expected message", e.getMessage()); // Optionally make sure you get the correct message, too 
} 

Il fail() si assicura di ricevere un errore se il codice non genera un'eccezione.

Io uso questo modello anche in JUnit 4 poiché di solito voglio essere sicuro che i valori corretti siano visibili nel messaggio di eccezione e @Test non può farlo.

+1

In JUnit 4, è possibile impostare un'eccezione prevista in @Test, ma è anche possibile utilizzare [ExpectedExceptions] (http://kentbeck.github.com/junit/javadoc/4.10/org/junit/rules/ExpectedException.html) che sono più flessibili e consentono di controllare il messaggio. – assylias

+0

Ah, non sapevo questa regola. È stato aggiunto con JUnit 4.7. –

1

nel metodo di prova, chiamare ajouter() all'interno di un .. catch blocco try, dando un valore di indice che dovrebbe causare la generazione di un'eccezione, con

  • una clausola catch che cattura IndexOutOfBoundsException: in quel caso ritorna dal tuo metodo di prova e quindi indica un passaggio.
  • un secondo catch clausola che cattura Throwable: in tal caso dichiarare un fallimento (chiamata fail()), perché il tipo sbagliato di eccezione è stato gettato
  • dopo la try .. catch dichiarare un fallimento (chiamata fail()), perché non fa eccezione è stato gettato.
2

Una cosa che si può fare è utilizzare un valore booleano per eseguire il test per il completamento e quindi è possibile utilizzare assert per convalidare l'eccezione è stato gettato:

boolean passed = false; 
try 
{ 
    //the line that throws exception 
    //i.e. illegal argument exception 
    //if user tries to set the property to null: 
    myObject.setProperty(null); 
} 
catch (IllegalArgumentException iaex) 
{ 
    passed = true; 
} 
assertTrue("The blah blah blah exception was not thrown as expected" 
       , passed); 

Utilizzando questo test, il test non sarà mai non riescono a eseguire ed è possibile verificare che venga generato un tipo di eccezione specifico.

1

estensione @ soluzione di Aaron con un po '(statica importazione) zucchero sintattico permette di scrivere:

expected(MyException.class, 
     new Testable() { 
      public void test() { 
      ... do thing that's supposed to throw MyException ... 
      } 
     }); 

Testable è come un Runnable che utilizza test) firma (gettando Throwable.

public class TestHelper { 
    public static void expected(Class<? extends Throwable> expectedClass, Testable testable) { 
     try { 
      testable.test(); 
      fail("Expected "+ expectedClass.getCanonicalName() +" not thrown."); 
     } catch (Throwable actual) { 
      assertEquals("Expected "+ expectedClass.getCanonicalName() +" to be thrown.", expectedClass, actual.getClass()); 
     } 
    } 

    interface Testable { 
     public void test() throws Throwable; 
    } 
} 

È possibile aggiungere il controllo del messaggio di eccezione come richiesto.