File tree Expand file tree Collapse file tree 1 file changed +59
-0
lines changed
junit-exception/src/test/java/com/hmkcode Expand file tree Collapse file tree 1 file changed +59
-0
lines changed 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+ }
You can’t perform that action at this time.
0 commit comments