About powermock static

阅读更多
mock官网:https://github.com/powermock/powermock/wiki/SuppressUnwantedBehavior
—————————————抑制static{}———————————————————

Suppress static initializer

Some times a thrid-party class does something in its static initializer (also called static constructor) that prevents you from unit testing your own class. It's also possible that your own class does something in a static initializer which you don't want to happen when you unit test your class. PowerMock can then simply suppress the static initialization of that class. You do this by specifying the @SuppressStaticInitializationFor annotation at the class-level or method-level of the test. For example let's say you want to unit-test the following class:

public class ExampleWithEvilStaticInitializer {

static {
System.loadLibrary("evil.dll");
}

private final String message;

public ExampleWithEvilStaticInitializer(String message) {
this.message = message;
}

public String getMessage() {
return message;
}
}
The problem here is that when the ExampleWithEvilStaticInitializer class is loaded the static code block will be executed and the System.loadLibrary("evil.dll") will be executed causing the unit test to fail (if the evil.dll cannot be loaded). To suppress this static initializer we do like this:

@SuppressStaticInitializationFor("org.mycompany.ExampleWithEvilStaticInitializer")
————————————————————————————————————————————

你可能感兴趣的:(mock)