0
我正在使用以下片段this答案。反思改变私人静态最终字段的值为单元测试
static void setFinalStatic(Field field, Object newValue) throws Exception {
field.setAccessible(true);
// remove final modifier from field
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newValue);
}
这里是我的MyClassTest
的一部分调用上述方法。(pathToFile
是MyClass
私人静态最终字段)。
public static void main (String ... args) {
try{
setFinalStatic(MyClass.class.getDeclaredField("pathtoFile"), "test-propFile.properties");
System.out.println(MyClass.class.getDeclaredField("pathtoFile"));// prints the original value of pathToFile.
// how do I access the modified value pathToFile here?
}
catch(Exception e){
e.printStackTrace();
}
此外,正在做这个,正确的方法来单元测试私人静态最终字段?任何意见/建议/链接表示赞赏。
我认为'MyClass'与'LMSValidation'不匹配是一个错字? – 2015-02-11 18:57:29
“*正在这样做,单元测试私有静态最终字段?”的正确方法是否有效?你有什么问题吗? – Pshemo 2015-02-11 18:58:13
@IanRoberts:更正了它。谢谢 – KodeSeeker 2015-02-11 19:49:28