SpringBoot单元测试

非 Y 不嫁゛ 提交于 2020-01-14 18:35:07

一、测试 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());
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!