Peter
Peter

Reputation: 5184

Fail JMockit test

When I run test classes separately, everything is fine and green. But when I run the test in Intellij all together some tests fail.

I reproduced that behavior with the following code:

public class TestSut {

    public static String test = "test";

    public static String test() {
        return test;
    }

}

This is the first 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");
    }   
}

This is the second 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");
    }

}

Make sure that Test1 runs before Test2 when executing the test together.

I guess, that the TestSut class is not reloaded after JMockit rewrote the class.

Is this a bug/behavior in Ideas test exec engine? Other ideas?

BTW: When I execute Tests with maven, everthing works like a charm.

Upvotes: 0

Views: 441

Answers (1)

Rogério
Rogério

Reputation: 16380

It's not a bug. The behavior resulting from the use of @Mocked(stubOutClassInitialization = true) is described in the relevant API documentation, which I reproduce below:

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.

Upvotes: 1

Related Questions