问题
I have a public class that has static variables, static blocks and static functions. I am testing one of the static function(say x) from my tester class , I have suppressed static block by using @SuppressStaticInitializationFor at the class level(Powermock) in the tester class . Now when I am running Jnunit test from my tester class I am getting null pointer exception when control reaches the above function that is using the static variables of the class.So my question is that does @SuppressStaticInitializationFor supress initialization of static variables too in the class or is it just limited to static blocks ? Any help is appreciated
回答1:
The documentation for @SuppressStaticInitialization says :-
- Use this annotation to suppress static initializers (constructors) for one or more classes.
This clearly suggests static initializers and variables havent been mentioned.
But you must take care that you must not pass the class name but you must pass the fully qualified name of class in parameter of @SuppressStaticInitialization
you need to do
@SuppressStaticInitialization(com.myPackage.Employee)
public class Employee{
.....
}
and you should not be doing this
@SuppressStaticInitialization(Employee.class)
public class Employee{
.....
}
hope you are doing this correctly.
The static variables are also not getting initialized,
the way out for this is using the Whitebox
class.Steps you need to perform are:-
- Do the suppression normally
- use the method
Whitebox.setInternalState(ClassName.class,fieldName,fieldValue)
to whichever value you want, (inside your test case) - Now you wont get a null pointer exception.
hope this helps!
Good luck!
来源:https://stackoverflow.com/questions/29665052/suppressstaticinitializationforpowermock