我很难找到一种设置类的静态字段的方法.基本上是这样的:
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是另一个类.
除了使用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测试
发布评论