【发布时间】:2018-06-20 14:19:40
【问题描述】:
我有一个带有从系统属性中提取的公共静态最终字段的接口。它看起来像这样:
public interface MyInterface {
public static final String MYFIELD = System.getProperty("MyField");
...
}
我正在编写一个使用该字段的单元测试。即使我在测试前在静态初始化程序中设置了系统属性,接口字段也会返回 null
System.out.println(System.getProperty("MYField")); //returns "MyField"
System.out.println(MyInterface.MYFIELD); //returns null
为什么没有设置接口字段?处理这种情况的最佳方法是什么?我不能只在测试中设置字段值,因为它是最终静态的。
更新:
我可能错过了一个重要的细节;我正在使用 Mocktio。它看起来像这样
public class MyTest {
static {System.setProperty("MyField", "MyValue");}
@Test
public void test1() {
try {
final MyInterface mockInterface = Mockito.mock(MyInterface.class);
...
}
}
}
【问题讨论】:
-
静态初始化器在类加载时执行。当第一次在代码中(而不是在导入中)引用一个类时,它就会被加载。因此,您需要在首次调用
MyInterface之前设置系统属性。