Created
September 28, 2015 16:24
-
-
Save stephan-mueller/c6d0108c915ed0bf441a to your computer and use it in GitHub Desktop.
JUnit test to demonstrate the handling of exceptions.
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
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