Field with @Mock annotation initialize vs. @BeforeAll

I have the following static mocking settings:

@ExtendWith(MockitoExtension.class)
TestClass{

@Mock
private static ClassB classBInstance;

    @BeforeAll
    static void setup(){
        MockedStatic<ClassA> mockedStatic = mockStatic(ClassA.class);
                mockedStatic.when(() -> ClassA.someMethod(ClassB.class)).thenReturn(classBInstance);
    }

    @Test
    void testMethod(){
        var mockedInstanceReference = ClassA.someMethod(ClassB.class);
    }

}

And here I am getting a null reference at mockedInstanceReference field. But in this configuration:

@ExtendWith(MockitoExtension.class)
TestClass{
    @Mock
    private static ClassB classBInstance;

        @Test
        void testMethod(){
            MockedStatic<ClassA> mockedStatic = mockStatic(ClassA.class);
                    mockedStatic.when(() -> ClassA.someMethod(ClassB.class)).thenReturn(classBInstance);
            var mockedInstanceReference = ClassA.someMethod(ClassB.class);
        }

}

I have no problem, I am getting he proper mocked reference. My question is:. Why? What is the order between @BerforeAll annotation processing and @Mock field initialisation in junit 5?

  • @BeforeAll is only executed once for your test class. @Mock fields are reassigned for every test method. mockedInstanceReference isn’t a field, it’s a local variable. IIRC mockStatic returns an AutoClosable and is only valid for the current thread.

    – 

  • I didn’t really get the connection between your thoughts and my issue. Could you pls elaborate them in details?

    – 

  • You asked what the order between BeforeAll and Mock is and I told you. @BeforeAll runs once for the class, @Mock fields are reassigned for every test method.

    – 

It is because you are using the wrong version of junit. Downgrade it to juit 4 and it will work.

Leave a Comment