'Java - How to mock static block with Mockito
Suppose I have legacy ElasticSearchIndexManager that is Singleton with static block as in the picture below that cannot be changed. My goal is to create a mock with any framework supported by latest java JDK.
Previously we used PowerMock that did the job as it had the ability to create mockStaticPartial that eliminated the static block at the startup of ElasticSearchIndexManager as in the code below.
PowerMock.mockStaticPartial(ElasticSearchIndexManager.class, "getInstance");
EasyMock.expect(
ElasticSearchIndexManager.getInstance(EasyMock.anyObject(AWSRegion.class)))
.andReturn(null).anyTimes();
The problem is that PowerMock is not supported with higher versions of JDK.
Now I've tried to use Mockito 3.7.7 and it helped a bit but did not solve my issue. Because we have legacy code in a 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 get this 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 the static block it will work. Is there any similar ability to create a partial static mock with Mockito?
Else, other ways are also welcome.
Thanks a lot.
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | nobody |

