Esiste un equivalente a ExpectedException o Assert.Throws di NUnit < in jUnit?ExpectedException in jUnit?
8
A
risposta
7
Junit4:
@Test(expected = org.dom4j.DocumentException.class)
void shouldThrowException() {
getFile(null);
}
junit3:
void testShouldThrowException() {
try {
getFile(null);
fail("Expected Exception DocumentException");
} catch(DocumentException e) {}
}
11
Si potrebbe anche prendere in considerazione uno sguardo alla classe ExpectedException che fornisce più ricca corrispondenza eccezione.
https://github.com/junit-team/junit/wiki/Exception-testing
Non solo è possibile abbinare la classe di eccezione, ma anche è possibile applicare matchers personalizzati per il suo messaggio.
2
Se si utilizza Groovy per i test di junit, è possibile utilizzare shouldFail.
Ecco un esempio utilizzando lo stile junit3:
void testShouldThrowException() {
def message = shouldFail(DocumentException) {
documentService.getFile(null)
}
assert message == 'Document could not be saved because it ate the homework.'
}
Problemi correlati
- 1. Come continuare il test dopo JUnit ExpectedException se lanciato?
- 2. ExpectedException Assert
- 3. Che è meglio, ExpectedException o @Test (expected =
- 4. @ExpectedException nei test delle unità di graal
- 5. Usa ExpectedException con Kotlin
- 6. UnitTest ExpectedException con più eccezioni
- 7. ExpectedException su TestMethod Visual Studio 2010
- 8. Impossibile risolvere Junit: Junit: 12
- 9. Come posso testare diverse eccezioni all'interno di un test usando una regola ExpectedException?
- 10. java.util.ConcurrentModificationException in JUnit tests
- 11. CollectionAssert in jUnit?
- 12. parametri @ in Junit 4
- 13. Mockito verifica dopo l'eccezione Junit 4.10
- 14. JUnit - espressione regolare prevista messaggio di eccezione
- 15. JUnit: NoClassDefFoundError: org/junit/corridore/manipolazione/filtro
- 16. Strano comportamento con NUnit, ExpectedException e rendimento restituito
- 17. Dove viene avviata la dichiarazione di JUnit Matcher #Con?
- 18. Classe teardown in junit 3?
- 19. JUnit XML "pacchetti" in hudson
- 20. Eseguire test JUnit in parallelo
- 21. Test Wrapping JUnit (in Eclipse)
- 22. Suite parametrizzate in Junit 4?
- 23. Log4j in JUnit Test case
- 24. Ottenere java.lang.ClassNotFoundException: javax.servlet.ServletContext in JUnit
- 25. JUnit - assertSame
- 26. Raggruppamento di test JUnit
- 27. JUnit Testing Exceptions
- 28. JUnit Exception Testing
- 29. JUnit opzionali test/richieste
- 30. Jenkins e JUnit
disponibile solo in Junit4 – jitter
Ho aggiornato questa risposta per includere un modo per fare questo in jUnit3 – j4y
La cosa buona di un approccio "JUnit3" è che si può quindi scrivere un caso di prova di eccezione per riga, mentre per l'approccio "JUnit4" occorrono cinque righe. Vedere la mia risposta per ulteriori informazioni: http://stackoverflow.com/a/15385613/974531 –