Skip to content

Instantly share code, notes, and snippets.

@wkorando
Last active March 3, 2019 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wkorando/9daa0d4cfc4859845b9ba3f0a8455381 to your computer and use it in GitHub Desktop.
Save wkorando/9daa0d4cfc4859845b9ba3f0a8455381 to your computer and use it in GitHub Desktop.
public class TestHandleExceptionsJUnit4 {
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test(expected = SpecificException.class)
public void testSpecificExceptionHandling() throws SpecificException {
onlyThrowsExceptions();
}
@Test(expected = Exception.class)//Passes because Exception is super type of SpecificException
public void testExceptionHandling() throws SpecificException {
onlyThrowsExceptions();
}
@Test(expected = SpecificException.class)
public void testExceptionHandlingVerifyExceptionFields() throws SpecificException {
try {
onlyThrowsExceptions();
} catch (SpecificException e) {
assertEquals("An exception was thrown!", e.getMessage());
throw e;
}
}
@Test
public void testUseExpectedException() throws SpecificException {
expectedException.expect(SpecificException.class);
expectedException.expectMessage("An exception was thrown!");
onlyThrowsExceptions();
}
@Test
public void testUseExpectedExceptionWithSuperType() throws SpecificException {
expectedException.expect(Exception.class);//Passes because Exception is super type of SpecificException
expectedException.expectMessage("An exception was thrown!");
onlyThrowsExceptions();
}
public void onlyThrowsExceptions() throws SpecificException {
throw new SpecificException("An exception was thrown!");
}
public class SpecificException extends Exception {
public SpecificException(String message) {
super(message);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment