3.5 Faking类初始化过程

如果某个类在需要在static块中完成一些初始化工作,而在测试时希望忽略掉这些初始化,就需要使用$clinit方法来fake类初始化过程。

public class Dependency {    

    //static赋值会被忽略
    public static String staticField = "staticField will not be initialized";
    
    //final可以赋值
    public static final String finalField = "finalField will be initialized";    
    
    //static语句块不会执行
    static {
        staticField = "staticField will not be initialized";    
    }
}
@Testpublic void TestMethod() {
    new MockUp() {
        @Mock
        void $clinit(){}
    };
    assertNull(new Dependency().staticField);
    assertNull(new Dependency().finalField);
}

你可能感兴趣的:(3.5 Faking类初始化过程)