11package  com .baeldung .reflection .exception .invocationtarget ;
22
3- import  static  org .junit .jupiter .api .Assertions .assertEquals ;
43import  static  org .junit .jupiter .api .Assertions .assertThrows ;
54
65import  java .lang .reflect .InvocationTargetException ;
76import  java .lang .reflect .Method ;
87
98import  org .junit .jupiter .api .Test ;
9+ import  org .slf4j .Logger ;
10+ import  org .slf4j .LoggerFactory ;
1011
1112public  class  InvocationTargetUnitTest  {
1213
14+     private  static  final  Logger  LOG  = LoggerFactory .getLogger (InvocationTargetUnitTest .class );
15+ 
1316    @ Test 
14-     public  void  whenCallingMethodThrowsException_thenAssertCauseOfInvocationTargetException () throws  Exception  {
17+     public  void  whenCallingMethodThrowsException_thenCorrect () throws  Exception  {
1518
1619        InvocationTargetExample  targetExample  = new  InvocationTargetExample ();
1720        Method  method  = InvocationTargetExample .class .getMethod ("divideByZeroExample" );
18-          
21+ 
1922        Exception  exception  = assertThrows (InvocationTargetException .class , () -> method .invoke (targetExample ));
20-         
21-         assertEquals (ArithmeticException .class , exception .getCause ().getClass ());
23+         LOG .error ("InvocationTargetException Thrown:" , exception );
24+     }
25+ 
26+     @ Test 
27+     public  void  whenCallingMethodThrowsException_thenPrintUnderlyingException () {
28+         try  {
29+             InvocationTargetExample  targetExample  = new  InvocationTargetExample ();
30+             Method  method  = InvocationTargetExample .class .getMethod ("divideByZeroExample" );
31+             method .invoke (targetExample );
32+         } catch  (InvocationTargetException  e ) {
33+             Throwable  cause  = e .getCause ();
34+             if  (cause  instanceof  ArithmeticException ) {
35+                 // handle ArithmeticException 
36+                 LOG .error ("InvocationTargetException caused by ArithmeticException:" , cause );
37+             } else  {
38+                 // handle other exceptions 
39+                 LOG .error ("The underlying exception of InvocationTargetException:" , cause );
40+             }
41+         } catch  (NoSuchMethodException  | IllegalAccessException  e ) {
42+             // for simplicity, rethrow reflection exceptions as RuntimeException 
43+             throw  new  RuntimeException (e );
44+         }
2245    }
23- }
46+ }
0 commit comments