Junit测试private方法

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);
		
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值