Domanda

Esiste un equivalente a ExpectedException o Assert di NUnit. Sposta < > in jUnit?

È stato utile?

Soluzione

Junit4:

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

junit3:

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

Altri suggerimenti

Potresti anche considerare di dare un'occhiata alla classe ExpectedException che fornisce una corrispondenza delle eccezioni più ricca.

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

Non solo puoi abbinare la classe di eccezione, ma puoi anche applicare abbinatori personalizzati al suo messaggio.

Se stai usando Groovy per i tuoi test junit puoi usare shouldFail .

Ecco un esempio usando lo stile junit3:

void testShouldThrowException() {
    def message = shouldFail(DocumentException) {
        documentService.getFile(null)
    }
    assert message == 'Document could not be saved because it ate the homework.'
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top