简体   繁体   中英

Java - How Mock static block with Mockito

Supposed I have legacy ElasticSearchIndexManager that is Singletone with static block as in the picture below that cannot be changed, my goal is create Mock with any framework supported by latest java JDK.

Previously we used PowerMock that did the Job as it had ability to create mockStaticPartial that eliminate static block at the startup of as ElasticSearchIndexManager as in the code below.

PowerMock.mockStaticPartial(ElasticSearchIndexManager.class, "getInstance");
        EasyMock.expect(
                ElasticSearchIndexManager.getInstance(EasyMock.anyObject(AWSRegion.class)))
                .andReturn(null).anyTimes();

在此处输入图像描述

The problem that it is PowerMock not supported with higher versions of JDK.

Now I've tried use Mockito 3.7.7 and it helped a bit but not solved my issue cause we have in Legacy code static block. In PowerMock we eliminate it by using mockStaticPartial.

POM.xml

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>3.7.7</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-inline</artifactId>
            <version>3.7.7</version>
            <scope>test</scope>
        </dependency>

// New code - with 3.7.7 Mockito
    @Test
        public void testMockElasticSearchIndexManager() {
            AWSRegion region = mock(AWSRegion.class);
    
            try (MockedStatic<ElasticSearchIndexManager> theMock = Mockito.mockStatic(ElasticSearchIndexManager.class)) {
                theMock.when(() -> ElasticSearchIndexManager.getInstance(region)).thenReturn(null);
            }

        assertEquals(null, ElasticSearchIndexManager.getInstance(region));
    }

Maybe I missed something? I got Exception before assertion org.mockito.exceptions.base.MockitoException: Cannot instrument class com.cloudally.index.ElasticSearchIndexManager because it or one of its supertypes could not be initialized

, If I remove static block it will work, How and is there any same ability to create with Mockito partial static mock, or other ways are welcome

Thanks a lot.

Can you try?

try (MockedStatic<ElasticSearchIndexManager> theMock = Mockito.mockStatic(ElasticSearchIndexManager.class)) {
    theMock.when(() -> ElasticSearchIndexManager.getInstance(region)).thenReturn(null);
    assertEquals(null, ElasticSearchIndexManager.getInstance(region));
}

Mock context is active only inside the try-with-resource block. When it goes outside the scope, it gets closed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM