Pergunta

Existe um equivalente para ExpectedException ou Assert.Throws do NUnit <> Na JUnit?

Foi útil?

Solução

junit4:

@Test(expected = org.dom4j.DocumentException.class)
void shouldThrowException() {
    getFile(null);
}

junit3:

void testShouldThrowException() {
    try {
      getFile(null);
      fail("Expected Exception DocumentException");
    } catch(DocumentException e) {}
}

Outras dicas

Você também pode considerar tomar um olhar para a classe ExpectedException que fornece mais rica correspondência exceção.

https://github.com/junit-team/junit/wiki / Exception-teste

Não só você pode combinar a classe de exceção, mas também você pode aplicar matchers personalizados para sua mensagem.

Se você estiver usando Groovy para seus testes JUnit você pode usar shouldFail .

Aqui está um exemplo usando o estilo junit3:

void testShouldThrowException() {
    def message = shouldFail(DocumentException) {
        documentService.getFile(null)
    }
    assert message == 'Document could not be saved because it ate the homework.'
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top