如何使用java反射机制测试私有方法

今天在项目中添加了一个私有方法,需要添加测试用例,学习了下用java反射机制测试私有方法,分享如下:

-首先私有方法如下(所在类为YoukuUploaderImpl):

private String checkUrl(String creativeUrl,CreativeAuditInfoView caiv){
        if (null == caiv) {
            log.error("creativeAuditInfoView is null.");
            return null;
        }
        if (null == targetService) {
            targetService = (TargetService) DspApplicationContextUtil.getContext().getBean("targetService");
        }
        List trafficList = null;
        try {
            trafficList = targetService.getAllTrafficByFlight(caiv.getFlightID());
        } catch (TargetException e) {
            log.error("YoukuUploaderImpl.checkUrl.trafficList", e);
            return null;
        }
        if (null != trafficList) {
            for (FlightTraffic traffic : trafficList) {
                if(traffic.getType().intValue() != 2){
                    return creativeUrl;
                }else{
                    break;
                }
            }
        }
        String[] spUrlPoint = creativeUrl.split("\\.");
        String endUrlPoint = spUrlPoint[spUrlPoint.length - 1];
        if(endUrlPoint!=null && endUrlPoint.toLowerCase().equals("html")){
            return creativeUrl;
        }
        String[] spUrlMark = creativeUrl.split("\\?");
        if(spUrlMark.length==2){
            return spUrlMark[0]+".html";
        }
        return null;
    }

测试类中是这样写的:

public String CheckUrlByReflect(String str)throws SecurityException, NoSuchMethodException, IllegalArgumentException, 
            IllegalAccessException, InvocationTargetException{
        YoukuUploaderImpl youkuUploaderImpl = new YoukuUploaderImpl();
        youkuUploaderImpl.setTargetService(targetService);
        Class clazz=YoukuUploaderImpl.class;
        Method method=clazz.getDeclaredMethod("checkUrl",new Class[]{String.class,CreativeAuditInfoView.class});
        method.setAccessible(true);
        Object object = method.invoke(youkuUploaderImpl, new Object[]{str,build(1,1)}); 
        String json = object==null ? "" : object.toString();
        log.info("json:"+json);
        return json;
    }

可以看出,利用反射机制调用私有方法时,首先需要new一个方法所在类的实例,还要获取这个类的字节码文件,然后用字节码文件获取相应的方法,并且要将方法设为可执行。
同时注意到反射机制调用方法的返回值是一个对象。

你可能感兴趣的:(JavaWeb)