Junit測試private方法
阿新 • • 發佈:2018-08-27
布爾 format void -h frame mat 取消 orm getclass
- package com.bill99.junit;
- public class ACase {
- private String echoRequest(String request) {
- return "Hello!"+request;
- }
- private String echoRequest() {
- return "Hello!";
- }
- }
- package com.bill99.junit;
- import java.lang.reflect.Method;
- import junit.framework.Assert;
- import org.junit.Before;
- import org.junit.Test;
- public class ACaseTest {
- ACase a =null;
- @Before
- public void setUp() throws Exception {
- a = new ACase();
- }
- @Test
- public void testNoParamEchoRequest() throws Exception {
- //測試沒有參數的echoRequest()方法
- Method testNoParamMethod = a.getClass().getDeclaredMethod("echoRequest", null);
- //Method對象繼承自java.lang.reflect.AccessibleObject,父類方法setAccessible可調
- //將此對象的 accessible 標誌設置為指示的布爾值。值為 true 則指示反射的對象在使用時應該取消 Java 語言訪問檢查。值為 false 則指示反射的對象應該實施 Java 語言訪問檢查。
- //要訪問私有方法必須將accessible設置為true,否則拋java.lang.IllegalAccessException
- testNoParamMethod.setAccessible(true);
- //調用
- Object result = testNoParamMethod.invoke(a, null);
- System.out.println(result);
- Assert.assertNotNull(result);
- }
- @Test
- public void testParamEchoRequest() throws Exception {
- //測試帶有參數的echoRequest(String request)方法
- Method testNoParamMethod = a.getClass().getDeclaredMethod("echoRequest",String.class);
- testNoParamMethod.setAccessible(true);
- //調用
- Object result = testNoParamMethod.invoke(a, "this is a test information");
- System.out.println(result);
- Assert.assertNotNull(result);
- }
- }
https://blog.csdn.net/iameyama/article/details/50411212
IDEA配置junit:
http://www.360doc.com/content/17/0701/11/10072361_667938060.shtml
Junit測試private方法