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

About powermock static

程序员文章站 2024-01-31 18:09:52
...
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