Skip to content

Instantly share code, notes, and snippets.

@stephan-mueller
Created September 28, 2015 16:24
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 stephan-mueller/c6d0108c915ed0bf441a to your computer and use it in GitHub Desktop.
Save stephan-mueller/c6d0108c915ed0bf441a to your computer and use it in GitHub Desktop.
JUnit test to demonstrate the handling of exceptions.
public class ExceptionHandlingTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test(expected = IndexOutOfBoundsException.class)
public void shouldFailForInvalidIndex() throws Exception {
new ArrayList<>().get(0);
}
@Test
public void shouldFailForInvalidIndexWithTryCatch() throws Exception {
try {
new ArrayList<>().get(0);
fail("Expected an IndexOutOfBoundsException to be thrown");
} catch (IndexOutOfBoundsException e) {
assertThat(e.getMessage()).isEqualTo("Index: 0, Size: 0");
}
}
@Test
public void shouldFailForInvalidIndexWithExpectedException() throws Exception {
thrown.expect(IndexOutOfBoundsException.class);
thrown.expectMessage("Index: 0, Size: 0");
new ArrayList<>().get(0); // execution will never get past this line
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment