一、测试 private 或 protect 方法
被测试类
public class ApiController {
protected String add(){
return "ok";
}
}
测试类
@Autowired
private ApiController apiController;
@Test
public void add() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
XxlSsoUser xxlSsoUser=new XxlSsoUser();
xxlSsoUser.setUserid("1889060");
Class [] parameterTypes = {XxlSsoUser.class,String.class,String.class,String.class};
Object[] arguments = {xxlSsoUser,"109","/xxs/test","测试数据"}; // 声明具体调用时传的参数
Method method = apiController.getClass().getDeclaredMethod(
"add", parameterTypes); // 声明调用哪个类的哪个方法
method.setAccessible(true);// 允许处理私有方法
BaseResult result = (BaseResult) method.invoke(apiController, arguments);// 具体调用
method.setAccessible(false);
Assert.assertEquals(100,result.getResponseCode());
}