PowerMock 测试 - 设置类的静态字段 [英] PowerMock testing - set static field of class
问题描述
我很难找到设置类的静态字段的方法.基本上是这样的:
I'm having difficulty finding a way to set a static field of a class. It's basically like this:
public class Foo{
// ...
private static B b = null;
}
其中 B 是另一个类.
where B is another class.
除了 setInternalStateFromContext()
之外,在 PowerMock 中还有什么方法可以做到这一点吗?使用上下文类方法设置一个字段似乎有点矫枉过正.
Is there any way to do this in PowerMock other than with setInternalStateFromContext()
? Using the context class method seems a bit of overkill for setting one field.
谢谢.
推荐答案
Whitebox.setInternalState(Foo.class, b);
只要您设置了一个非空值,和就可以工作,如果只有一个字段具有 B
的类.如果您不能依赖这种奢侈,您必须提供字段名称并将 null
强制转换为您要设置的类型.在这种情况下,您需要编写如下内容:
Works as long as you set a non-null value, and if theres only one field with the class of B
. If you can't rely on that luxury, you have to provide the field-name and cast the null
to the type you want to set. In that case you would need to write something like this:
Whitebox.setInternalState( Foo.class, "b", (B)null );
这篇关于PowerMock 测试 - 设置类的静态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!