Testing exceptions can be done with the @Test annotation and its expected property. The message of the exception has to be asserted in a catch-block. This test seems a bit cumbersome.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Test(expected = IllegalArgumentException.class) | |
public void exceptionTesting() { | |
try { | |
throw new IllegalArgumentException("id must not be null"); | |
} | |
catch(IllegalArgumentException iae) { | |
assertEquals("id must not be null", iae.getMessage()); | |
throw iae; | |
} | |
} |
Since JUnit 4.7, it is possible to use the @Rule annotation to expect exceptions. In this way, the test can be expressed quite more elegantly.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Rule | |
public ExpectedException thrown = ExpectedException.none(); | |
@Test | |
public void shouldThrowExpectedException(){ | |
thrown.expect(IllegalArgumentException.class); | |
thrown.expectMessage("id must not be null"); | |
throw new IllegalArgumentException("id must not be null"); | |
} |
In JUnit 5, we use Java 8 Lambdas to describe the same test.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Test | |
void exceptionTesting() { | |
Throwable exception = expectThrows(IllegalArgumentException.class, () -> { | |
throw new IllegalArgumentException("id must not be null"); | |
}); | |
assertEquals("id must not be null", exception.getMessage()); | |
} |