Junit test private methods

Java code  Collection Code

  1. package com.bill99.junit;  
  2.   
  3. public class ACase {  
  4.   
  5.     private String echoRequest(String request) {  
  6.         return "Hello!"+request;  
  7.     }  
  8.       
  9.     private String echoRequest() {  
  10.         return "Hello!";  
  11.     }  
  12. }  

 

Java code  Collection Code

  1. package com.bill99.junit;  
  2.   
  3.   
  4. import java.lang.reflect.Method;  
  5.   
  6. import junit.framework.Assert;  
  7.   
  8. import org.junit.Before;  
  9. import org.junit.Test;  
  10.   
  11. public class ACaseTest {  
  12.   
  13.     ACase a =null;  
  14.       
  15.     @Before  
  16.     public void setUp() throws Exception {  
  17.         a = new ACase();  
  18.     }  
  19.   
  20.     @Test  
  21.     public void testNoParamEchoRequest() throws Exception {  
  22.         // test echoRequest no parameters () method  
  23.         Method testNoParamMethod = a.getClass().getDeclaredMethod("echoRequest", null);   
  24.         // Method object inherits from java.lang.reflect.AccessibleObject, adjustable super method setAccessible  
  25.         // Set the accessible flag object to the indicated boolean value. A value of true indicates that the object is reflected in the use of the Java language access checks should be canceled. Value of false indicates that the object should be reflected in the Java language access checks embodiment.                                            
  26.         // To access private methods accessible must be set to true, otherwise throw java.lang.IllegalAccessException  
  27.         testNoParamMethod.setAccessible(true);   
  28.         //transfer  
  29.         Object result = testNoParamMethod.invoke(a, null);  
  30.         System.out.println(result);  
  31.         Assert.assertNotNull(result);  
  32.           
  33.     }  
  34.       
  35.     @Test  
  36.     public void testParamEchoRequest() throws Exception {  
  37.         // test echoRequest with parameters (String request) method  
  38.         Method testNoParamMethod = a.getClass().getDeclaredMethod("echoRequest",String.class);   
  39.         testNoParamMethod.setAccessible(true);   
  40.         //transfer  
  41.         Object result = testNoParamMethod.invoke(a, "this is a test information");  
  42.         System.out.println(result);  
  43.         Assert.assertNotNull(result);  
  44.           
  45.     }  
  46.   
  47. }  
Published 36 original articles · won praise 162 · views 620 000 +

Guess you like

Origin blog.csdn.net/qq_19004627/article/details/103417995