GeezerVison is showing github.com — AppTest.java · ansibee/Java-tools@d325b97
File tree
Expand file treeCollapse file tree
Open diff view settings
junit-exception/src/test/java/com/hmkcode
Expand file treeCollapse file tree
Open diff view settings
Collapse file
Copy file name to clipboard +59Lines changed: 59 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
|
| 1 | +package com.hmkcode; |
| 2 | + |
| 3 | +import java.util.LinkedList; |
| 4 | + |
| 5 | +import org.junit.Rule; |
| 6 | +import org.junit.Test; |
| 7 | +import org.junit.rules.ExpectedException; |
| 8 | +import org.junit.runner.RunWith; |
| 9 | +import org.junit.runners.JUnit4; |
| 10 | + |
| 11 | +import static org.junit.Assert.assertThat; |
| 12 | +import static org.junit.Assert.fail; |
| 13 | +import static org.hamcrest.CoreMatchers.is; |
| 14 | + |
| 15 | + |
| 16 | + |
| 17 | +@RunWith(JUnit4.class) |
| 18 | +public class AppTest |
| 19 | +{ |
| 20 | + |
| 21 | + // ( 1 ) Simple way to test exception |
| 22 | + @Test(expected= NullPointerException.class) |
| 23 | + public void testNull() { |
| 24 | + String str = null; |
| 25 | + str.toUpperCase(); |
| 26 | + } |
| 27 | + |
| 28 | + // ( 2 ) Test by tyr/catch (test exception message) |
| 29 | + @Test |
| 30 | + public void testExceptionMessage(){ |
| 31 | + try{ |
| 32 | + new LinkedList<Object>().get(0); |
| 33 | + |
| 34 | + //if no exception thrown the test will fail with the below message. |
| 35 | + fail("Expected an IndexOutOfBoundsException to be thrown"); |
| 36 | + |
| 37 | + } catch (IndexOutOfBoundsException anIndexOutOfBoundsException) { |
| 38 | + |
| 39 | + //if no exception message is not the same the test will fail with the below message. |
| 40 | + assertThat(anIndexOutOfBoundsException.getMessage(), is("Index: 0, Size: 0")); |
| 41 | + } |
| 42 | + |
| 43 | + } |
| 44 | + |
| 45 | + //( 3 ) Test by @Rule & ExpectedException.expect() | ExpectedException.expectMessage() |
| 46 | + @Rule |
| 47 | + public ExpectedException thrown = ExpectedException.none(); |
| 48 | + |
| 49 | + @Test |
| 50 | + public void testExceptionByRule() throws ArithmeticException { |
| 51 | + |
| 52 | + thrown.expect(ArithmeticException.class); |
| 53 | + thrown.expectMessage("/ by zero"); |
| 54 | + |
| 55 | + double d = 1 / 0; |
| 56 | + } |
| 57 | + |
| 58 | + |
| 59 | +} |