Junit測試private方法


  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. }  
  13.  
 
  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.         //測試沒有參數的echoRequest()方法  
  23.         Method testNoParamMethod = a.getClass().getDeclaredMethod("echoRequest", null);   
  24.         //Method對象繼承自java.lang.reflect.AccessibleObject,父類方法setAccessible可調  
  25.         //將此對象的 accessible 標志設置為指示的布爾值。值為 true 則指示反射的對象在使用時應該取消 Java 語言訪問檢查。值為 false 則指示反射的對象應該實施 Java 語言訪問檢查。                                            
  26.         //要訪問私有方法必須將accessible設置為true,否則拋java.lang.IllegalAccessException  
  27.         testNoParamMethod.setAccessible(true);   
  28.         //調用  
  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.         //測試帶有參數的echoRequest(String request)方法  
  38.         Method testNoParamMethod = a.getClass().getDeclaredMethod("echoRequest",String.class);   
  39.         testNoParamMethod.setAccessible(true);   
  40.         //調用  
  41.         Object result = testNoParamMethod.invoke(a, "this is a test information");  
  42.         System.out.println(result);  
  43.         Assert.assertNotNull(result);  
  44.           
  45.     }  
  46.   
  47. }  

https://blog.csdn.net/iameyama/article/details/50411212

IDEA配置junit:

http://www.360doc.com/content/17/0701/11/10072361_667938060.shtml


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM