欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[UnitTest] Unit Test 测试非public变量/方法[转载] 博客分类: JUnit4转载 JUnitUnitTest 

程序员文章站 2024-02-14 20:33:04
...

From: http://*.com/questions/34571/how-to-test-a-class-that-has-private-methods-fields-or-inner-classes

 

If you have somewhat of a legacy application, and you're not allowed to change the visibility of your methods, the best way to test private methods is to use reflection.

Internally we're using helpers to get/set private and private static variables as well as invoke private and private static methods. The following patterns will let you do pretty much anything related to the private methods and fields. Of course you can't change private static finalvariables through reflection.

 

Method:

Method method = targetClass.getDeclaredMethod(methodName, argClasses);
method.setAccessible(true);
return method.invoke(targetObject, argObjects);

 

Field:

Field field = targetClass.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, value);

 

Notes:
targetClass.getDeclaredMethod(methodName, argClasses) lets you look into private methods. The same thing applies for getDeclaredField.
* The setAccessible(true) is required to play around with privates.

相关标签: JUnit UnitTest