The major unit testing frameworks support verifying an exception.
Consider this method:
public boolean throwIfBlank(String input) {
if(input == null || input.trim().isEmpty()) {
throw new IllegalArgumentException("Input should not be blank.");
}
return true;
}
For JUnit 4, you could use the expected
attribute of the @Test
annotation to verify that an exception is thrown. If the exception is not thrown, then the unit test will be failed.
// JUnit 4
@Test( expected = IllegalArgumentException.class )
public void testBlankStringThrowsException() {
classUnderTest.throwIfBlank("");
// test will automatically fail if exception is NOT thrown
}
Similarly, in JUnit 5 you can explicitly assert that something is thrown using assertThrows
:
@Test
void testBlankStringThrowsException() {
assertThrows(IllegalArgumentException.class, () -> classUnderTest.throwIfBlank(""));
}
And finally, TestNG's @Test
annotation supports a variety of attributes to verify that a particular exception is thrown:
@Test(
expectedExceptions = IllegalArgumentException.class,
expectedExceptionsMessageRegExp = "Input should not be blank."
)
public void testBlankStringThrowsException {
classUnderTest.throwIfBlank("");
}
Of course, you can always wrap your test method in a try-catch
block and explicitly call fail()
if you do not throw the exception; generally this old-school method is not required but for completeness:
@Test
public void testBlankStringThrowsException() {
try {
classUnderTest.throwIfBlank("");
fail("Blank string should have thrown an IllegalArgumentException!");
} catch (IllegalArgumentException e) {
// expected
} catch (Exception e) {
fail("Expected an IllegalArgumentException but threw: " + e);
}
}