如何通过java反射的方式对java私有方法进行单元测试

待测试的私有方法:

import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import springfox.documentation.service.ApiInfo;

import java.lang.reflect.Method;
public class SwaggerAPIPluginConfigTest {
SwaggerAPIPluginConfig swaggerAPIPluginConfig;
@BeforeClass
public void setUp(){
swaggerAPIPluginConfig = new SwaggerAPIPluginConfig();
}
//通过反射的方式对私有方法进行单元测试
@Test
public void testApiInfo() throws Exception {
Class<SwaggerAPIPluginConfig> swaggerAPIPluginConfig = SwaggerAPIPluginConfig.class;
Object instance = swaggerAPIPluginConfig.newInstance();
Method method = swaggerAPIPluginConfig.getDeclaredMethod("apiInfo", new Class[]{});
method.setAccessible(true);
ApiInfo result = (ApiInfo)method.invoke(instance,new Object[]{});
String expected="XXXXXXXXXX";
Assert.assertEquals(result.getTitle(),expected);
}
原文地址:https://www.cnblogs.com/laoqing/p/7517263.html