Junit测试private方法

时间:2023-03-09 07:10:44
Junit测试private方法
  1. package com.bill99.junit;
  2. public class ACase {
  3. private String echoRequest(String request) {
  4. return "Hello!"+request;
  5. }
  6. private String echoRequest() {
  7. return "Hello!";
  8. }
  9. }
  1. package com.bill99.junit;
  2. import java.lang.reflect.Method;
  3. import junit.framework.Assert;
  4. import org.junit.Before;
  5. import org.junit.Test;
  6. public class ACaseTest {
  7. ACase a =null;
  8. @Before
  9. public void setUp() throws Exception {
  10. a = new ACase();
  11. }
  12. @Test
  13. public void testNoParamEchoRequest() throws Exception {
  14. //测试没有参数的echoRequest()方法
  15. Method testNoParamMethod = a.getClass().getDeclaredMethod("echoRequest", null);
  16. //Method对象继承自java.lang.reflect.AccessibleObject,父类方法setAccessible可调
  17. //将此对象的 accessible 标志设置为指示的布尔值。值为 true 则指示反射的对象在使用时应该取消 Java 语言访问检查。值为 false 则指示反射的对象应该实施 Java 语言访问检查。
  18. //要访问私有方法必须将accessible设置为true,否则抛java.lang.IllegalAccessException
  19. testNoParamMethod.setAccessible(true);
  20. //调用
  21. Object result = testNoParamMethod.invoke(a, null);
  22. System.out.println(result);
  23. Assert.assertNotNull(result);
  24. }
  25. @Test
  26. public void testParamEchoRequest() throws Exception {
  27. //测试带有参数的echoRequest(String request)方法
  28. Method testNoParamMethod = a.getClass().getDeclaredMethod("echoRequest",String.class);
  29. testNoParamMethod.setAccessible(true);
  30. //调用
  31. Object result = testNoParamMethod.invoke(a, "this is a test information");
  32. System.out.println(result);
  33. Assert.assertNotNull(result);
  34. }
  35. }

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

IDEA配置junit:

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