失败的 JMockit 测试

Fail JMockit test

当我 运行 单独测试 classes 时,一切正常且绿色。但是当我 运行 Intellij 中的测试全部一起时,一些测试失败了。

我使用以下代码重现了该行为:

public class TestSut {

    public static String test = "test";

    public static String test() {
        return test;
    }

}

这是第一个测试:

@RunWith(JMockit.class)
public class Test1 {

    @Mocked(stubOutClassInitialization = true)
    TestSut test;

    @Before
    public void setUp() throws Exception {

    }

    @Test public void test_mocked_test_method() throws Exception {

        new Expectations() {{
            TestSut.test();
            result = "new Test";
        }};

        assertThat(TestSut.test()).isEqualTo("new Test");
    }   
}

这是第二个测试:

@RunWith(JMockit.class)
public class Test2 {

    @Before
    public void setUp() throws Exception {

    }

    @Test
    public void test_real_test_method() throws Exception {

        assertThat(TestSut.test()).isEqualTo("test");
    }

}

确保在Test2之前Test1运行秒一起执行测试。

我猜,在 JMockit 重写了 class 之后,TestSut class 没有重新加载。

这是 Ideas 测试执行引擎中的 bug/behavior 吗?其他想法?

顺便说一句:当我用 maven 执行测试时,一切都很顺利。

这不是错误。使用 @Mocked(stubOutClassInitialization = true) 导致的行为在相关 API documentation 中进行了描述,我在下面重现:

Indicates whether static initialization code in the mocked class should be stubbed out or not. Static initialization includes the execution of assignments to static fields of the class and the execution of static initialization blocks, if any.

By default, static initialization code in a mocked class is not stubbed out. The JVM will only perform static initialization of a class once, so stubbing out the initialization code can have unexpected consequences. Static initialization will occur the first time the class is instantiated, has a static method called on it, or has a static field whose value is defined at runtime accessed; these are the only events which prompt the JVM to initialize a class. If the original class initialization code was stubbed out, then it will not be there to be executed at the time of static initialization, potentially leaving static fields null and later causing NullPointerException's to occur.