是否有一种方法可以使用反射测试私有内部类的方法?在下面的代码中,我们如何测试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) {
//
}
}
}发布于 2016-07-12 22:47:46
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);
}
}发布于 2016-06-22 18:43:36
通过反射和使用setAccessible(true),这是可能的,但这将是困难的,特别是当您有私有的非静态内部类时。
最有趣的问题是:,你为什么要这么做?
这些内部类和方法应该影响被测试的外部类的行为。所以请测试一下那堂课!
尝试测试类的私有部分主要是延迟测试的信号,因为您可能需要更少的设置,您有没有测试的遗留代码,并且只想测试我的更改。但对不起,那是没用的。
这样做的所有努力都是无用的,相反,测试完整的类!
发布于 2016-06-22 19:00:57
我没必要处理这件事,但我认为这是个好问题。我不能百分之百地肯定这件事,但也许这会奏效。
Outer.class.getDeclaredClasses()[0].getDeclaredMethod("func-1").invoke(null);我目前没有环境来测试它。但也许会有帮助。
https://stackoverflow.com/questions/37975725
复制相似问题