I'm using the following snippet from this answer .
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);
}
Here's a part of my MyClassTest
that calls the above method.(pathToFile
is a private static final field in MyClass
).
public static void main (String ... args) {
try{
setFinalStatic(MyClass.class.getDeclaredField("pathtoFile"), "test-propFile.properties");
System.out.println(LMSValidation.class.getDeclaredField("pathtoFile"));// prints the original value of pathToFile.
// how do I access the modified value pathToFile here?
}
catch(Exception e){
e.printStackTrace();
}
Also, is doing this, the right approach to unit testing a private static final field? Any comments/suggestions/links appreciated.
Aucun commentaire:
Enregistrer un commentaire