现实的业务场景中,可能需要对spring的实现类的私有方法进行测试。

场景描述:

比如xxxservice里有 两个函数a、函数b。

而实现类xxxserviceimpl中实现了函数a、函数b,还包含私有方法函数c和函数d。

要写一个xxxtestcontroller来调用xxxserviceimpl的函数c。

面临几个问题:

1、如果注入接口,则无法调用实现类的私有类。

2、如果注入实现类,则需要将实现类里的私有方法改为公有的,而且需要设置@enableaspectjautoproxy(proxytargetclass = true)使用cglib代理方式

如果单纯为了测试而接口中定义实现类的私有方法或者为了测试而将私有方法临时改为公有方法,显然不太合适。

解决方案:

可以通过cglib注入实现类的子类,如果是gradle项目也可以使用aspect插件,将切面代码在编译器织入实现类中注入的类型则为实现类,然后通过反射设置为可访问来调用私有方法。

方案一 使用beanutils.finddeclaredmethod反射方法

反射调用代码:

beaninvokeutil

public class beaninvokeutil {
 
  public class invokeparams {
 
// 方法名称(私有)
    private string methodname;
 
// 参数列表类型数组
    private class<?>[] paramtypes;
// 调用的对象
    private object object;
 
// 参数列表数组(如果不为null,需要和paramtypes对应)
    private object[] args;
 
    public invokeparams() {
      super();
    }
 
    public invokeparams(object object, string methodname, class<?>[] paramtypes, object[] args) {
      this.methodname = methodname;
      this.paramtypes = paramtypes;
      this.object = object;
      this.args = args;
    }
 
    public string getmethodname() {
      return methodname;
    }
 
    public void setmethodname(string methodname) {
      this.methodname = methodname;
    }
 
    public class<?>[] getparamtypes() {
      return paramtypes;
    }
 
    public void setparamtypes(class<?>[] paramtypes) {
      this.paramtypes = paramtypes;
    }
 
    public object getobject() {
      return object;
    }
 
    public void setobject(object object) {
      this.object = object;
    }
 
    public object[] getargs() {
      return args;
    }
 
    public void setargs(object[] args) {
      this.args = args;
    }
  }
 
  public static object invokeprivatemethod(invokeparams invokeparams) throws invocationtargetexception, illegalaccessexception {
    // 参数检查
    checkparams(invokeparams);
    // 调用
    return doinvoke(invokeparams);
  }
 
  private static object doinvoke(invokeparams invokeparams) throws invocationtargetexception, illegalaccessexception {
    object object = invokeparams.getobject();
    string methodname = invokeparams.getmethodname();
    class<?>[] paramtypes = invokeparams.getparamtypes();
    object[] args = invokeparams.getargs();
 
    method method;
    if (paramtypes == null) {
      method = beanutils.finddeclaredmethod(object.getclass(), methodname);
    } else {
      method = beanutils.finddeclaredmethod(object.getclass(), methodname, paramtypes);
    }
    method.setaccessible(true);
    if (args == null) {
      return method.invoke(object);
    }
    return method.invoke(object, args);
 
  }
 
  private static void checkparams(invokeparams invokeparams) {
    object object = invokeparams.getobject();
    if (object == null) {
      throw new illegalargumentexception("object can not be null");
    }
    string methodname = invokeparams.getmethodname();
    if (stringutils.isempty(methodname)) {
      throw new illegalargumentexception("methodname can not be empty");
    }
 
    // 参数类型数组和参数数组要对应
    class<?>[] paramtypes = invokeparams.getparamtypes();
    object[] args = invokeparams.getargs();
 
    boolean illegal = true;
    if (paramtypes == null && args != null) {
      illegal = false;
    }
    if (args == null && paramtypes != null) {
      illegal = false;
    }
    if (paramtypes != null && args != null && paramtypes.length != args.length) {
      illegal = false;
    }
    if (!illegal) {
      throw new illegalargumentexception("paramtypes length != args length");
    }
  }
}

使用方式:

使用时通过cglib方式注入实现类或者将切面代码编译器织入实现类的方式,然后注入bean。

@autowired private xxxservice xxxservice;

然后填入调用的对象,待调用的私有方法,参数类型数组和参数数组。

beaninvokeutil.invokeprivatemethod(new beaninvokeutil()
            .new invokeparams(xxxservice, "someprivatemethod", null, null));

注意这时注入的xxxservice的类型为 xxxserviceimpl。

如果需要返回值,可以获取该调用方法的返回值。

方案二:使用jdk和cglib工具获取真实对象

测试类

public class test {
  @autowired
  serviceimpl serviceimpl;

  @test
  public void test() throws exception {
  class<?> clazz = class.forname("serviceimpl");
  method method = clazz.getdeclaredmethod("methoda");
  method.setaccessible(true);
  object target = reflectionutil.gettarget(serviceimpl);
  // 注意,这里不能直接用serviceimpl,因为它已经被spring管理,
  // 变成serviceimpl真实实例的代理类,而代理类中并没有私有方法,所以需要先获取它的真实实例
  method.invoke(target);
  }
}

获取spring 代理对象的真实实例的工具类,适用于两种动态代理情况:jdk和cglib

public class reflectionutil {
  /**
   * 获取spring 代理对象的真实实例
   * @param proxy 代理对象
   * @return
   * @throws exception
   */
  public static object gettarget(object proxy) throws exception {
    if(!aoputils.isaopproxy(proxy)) {
      return proxy;//不是代理对象
    }

    if(aoputils.isjdkdynamicproxy(proxy)) {
      return getjdkdynamicproxytargetobject(proxy);
    } else { //cglib
      return getcglibproxytargetobject(proxy);
    }
  }

  private static object getcglibproxytargetobject(object proxy) throws exception {
    field h = proxy.getclass().getdeclaredfield("cglib$callback_0");
    h.setaccessible(true);
    object dynamicadvisedinterceptor = h.get(proxy);
    field advised = dynamicadvisedinterceptor.getclass().getdeclaredfield("advised");
    advised.setaccessible(true);
    object target = ((advisedsupport)advised.get(dynamicadvisedinterceptor)).gettargetsource().gettarget();
    return target;
  }

  private static object getjdkdynamicproxytargetobject(object proxy) throws exception {
    field h = proxy.getclass().getsuperclass().getdeclaredfield("h");
    h.setaccessible(true);
    aopproxy aopproxy = (aopproxy) h.get(proxy);
    field advised = aopproxy.getclass().getdeclaredfield("advised");
    advised.setaccessible(true);
    object target = ((advisedsupport)advised.get(aopproxy)).gettargetsource().gettarget();
    return target;
  }
}

另外还有一个更好的开源工具 powermock https://github.com/powermock/powermock,感兴趣的同学可以研究一下

以上就是spring实现类私有方法测试通用方案的详细内容,更多关于spring类私有方法的资料请关注www.887551.com其它相关文章!