测试私有内部类
目标代码:
public class TestDemo {
public void methodA ( ) {
}
private static class TestClass {
private String testString;
TestClass ( ) { }
public boolean testMethod ( String str) {
return true ;
}
}
}
单元测试代码:
class test {
public static void main ( String[ ] args) throws Exception {
Object object = null;
Class< TestDemo> testDemoClass = TestDemo. class ;
Class< ? > [ ] declaredClasses = testDemoClass. getDeclaredClasses ( ) ;
for ( Class clazz : declaredClasses) {
int mod = clazz. getModifiers ( ) ;
String modifier = Modifier. toString ( mod) ;
if ( modifier. contains ( "private" ) ) {
String simpleName = clazz. getSimpleName ( ) ;
Constructor[ ] declaredConstructors = clazz. getDeclaredConstructors ( ) ;
AccessibleObject. setAccessible ( declaredConstructors, true ) ;
for ( Constructor constructor : declaredConstructors) {
object = constructor. newInstance ( ) ;
if ( object != null) break ; ;
}
Field testString = clazz. getDeclaredField ( "testString" ) ;
testString. setAccessible ( true ) ;
testString. set ( object, "想要设置的值" ) ;
Method testMethod = clazz. getMethod ( "testMethod" , String. class ) ;
testMethod. setAccessible ( true ) ;
Assert. assertTrue ( ( Boolean) testMethod. invoke ( object, "方法参数值" ) ) ;
break ;
}
}
}
}