- 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 {
- // test echoRequest no parameters () method
- Method testNoParamMethod = a.getClass().getDeclaredMethod("echoRequest", null);
- // Method object inherits from java.lang.reflect.AccessibleObject, adjustable super method setAccessible
- // 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.
- // To access private methods accessible must be set to true, otherwise throw java.lang.IllegalAccessException
- testNoParamMethod.setAccessible(true);
- //transfer
- Object result = testNoParamMethod.invoke(a, null);
- System.out.println(result);
- Assert.assertNotNull(result);
- }
- @Test
- public void testParamEchoRequest() throws Exception {
- // test echoRequest with parameters (String request) method
- Method testNoParamMethod = a.getClass().getDeclaredMethod("echoRequest",String.class);
- testNoParamMethod.setAccessible(true);
- //transfer
- Object result = testNoParamMethod.invoke(a, "this is a test information");
- System.out.println(result);
- Assert.assertNotNull(result);
- }
- }