[英]Using reflection to test methods of inner private class
有没有一种方法可以使用反射来测试私有内部类的方法? 在下面的代码中,我们如何测试func-1和func-2
public class Outer extends AbstractOuter {
private final Properties properties;
public Outer(Properties properties) {
this.properties = properties;
}
private class Inner extends AbstractInner {
private int numOfProperties;
@Override
void func-1() throws Exception {
//
}
private int func-2(long l) {
//
}
}
}
package SalesUnitsIntoCarton.mySolution;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class UtilityReflections {
private static final Object[] EMPTY = {};
/**
* This method returns a value, returned by the method of a private inner class, of a given object instance.
*
* @param outerClassInstance This parameter needs to be an instance of the outer class that contains the private inner class.
* @param attributeNameOfInnerClassInOuterClass This is the name of the attribute that is an inner class type, within the outer class.
* @param innerClassName This is the class name of the inner class.
* @param methodNameOfInnerClass This is the name of the method inside the inner class that should be called.
* @return Returns the value returned by the method of the inner class. CAUTION: needs casting since its of type {@link Object}
*
* @throws SecurityException
* @throws NoSuchFieldException
* @throws ClassNotFoundException
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws Exception
*/
public static <T extends Object> Object executeInnerClassMethod(T outerClassInstance, String attributeNameOfInnerClassInOuterClass, String innerClassName, String methodNameOfInnerClass)
throws NoSuchFieldException, SecurityException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
final Class<?> outerClass = outerClassInstance.getClass();
final Field field = outerClass.getDeclaredField(attributeNameOfInnerClassInOuterClass);
field.setAccessible(true);
Class<?> innerClass = Class.forName(innerClassName);
innerClass = field.getType();
//access the method
final Method method = innerClass.getDeclaredMethod(methodName, new Class<?>[]{});
method.setAccessible(true);
return method.invoke(field.get(outerClassInstance), EMPTY);
}
}
通过反射和使用setAccessible(true)
可以实现某种方式,但是特别是当您拥有私有的非静态内部类时,这将很难。
最有趣的问题是: 为什么要这么做呢?
这些内部类和方法应该影响所测试的外部类的行为。 因此,请测试该课程!
尝试测试类的私有部分通常是懒惰测试的信号,因为您可能需要较少的设置,您有没有测试的旧代码,并且只想测试我的更改 。 但是抱歉,这没用。
这样做的全部努力是没有用的,而是测试整个课程!
我没有处理这个问题,但是我认为这是一个很好的问题。 我对此不是100%的把握,但是也许可以。
Outer.class.getDeclaredClasses()[0].getDeclaredMethod("func-1").invoke(null);
我目前没有环境可以测试。 但也许有帮助。
您可以使用Mockito使用模拟对象对此进行测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.