抑制不想要的行为
总览
- 在测试用例的类上使用
@RunWith(PowerMockRunner.class)
注解。 - 在测试用例的类上结合使用
@PrepareForTest(ClassWithEvilParentConstructor.class)
和suppress(constructor(EvilParent.class))
注解,以禁止调用EvilParent类的所有构造函数。 - 使用
Whitebox.newInstance(ClassWithEvilConstructor.class)
方法去实例化一个类而无须调用其构造函数。 - 使用
@SuppressStaticInitializationFor("org.mycompany.ClassWithEvilStaticInitializer")
注解移除类org.mycompany.ClassWithEvilStaticInitializer
的静态初始化器。 - 在类上使用
@PrepareForTest(ClassWithEvilMethod.class)
注解结合suppress(method(ClassWithEvilMethod.class, "methodName"))
去抑制类ClassWithEvilMethod中的 "methodName" 方法。 - 在类上使用
@PrepareForTest(ClassWithEvilField.class)
注解结合suppress(field(ClassWithEvilField.class, "fieldName"))
去抑制类 ClassWithEvilField 中的"fieldName" 字段。
您可以在此处找到成员修改和成员匹配器方法:
org.powermock.api.support.membermodification.MemberModifier
org.powermock.api.support.membermodification.MemberMatcher
示例
有时,您甚至希望抑制某些构造函数,方法或静态初始化程序的行为,以便对您自己的代码进行单元测试。一个典型的例子是您的类需要从某种第三方框架中的另一个类扩展而来。当第3方类在其构造函数中执行某些操作而导致您无法对自己的代码进行单元测试时,就会出现问题。例如,由于某种原因,框架可能尝试加载dll或访问网络或文件系统。让我们看一些例子。
禁止超类构造函数
作为示例,让我们看一下名为ExampleWithEvilParent
的类,它非常简单:
public class ExampleWithEvilParent extends EvilParent {
private final String message;
public ExampleWithEvilParent(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
这似乎是一个易于进行单元测试的类(实际上如此简单,您可能不应该对其进行测试,但是为了演示起见,让我们继续进行测试)。但是,等等,让我们看一下EvilParent
类的样子:
public class EvilParent {
public EvilParent() {
System.loadLibrary("evil.dll");
}
}
该父类尝试加载一个dll文件,该文件在您对ExampleWithEvilPa