How to mock a static method of util class of a package using spring dependency injection

Viewed 284

I have a package using spring dependency injection for its unit tests using following code.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "<xml_location>" })
@WebAppConfiguration

I need to add a static method in the util class and need to mock it to prevent existing unit tests to fail. I tried using PowerMock but getting different errors like the following ones.

<class_name> not prepared for test.
org.powermock.api.mockito.ClassNotPreparedException
Failed to load ApplicationContext

Can someone please point to an example where this was done before?

1 Answers

You can use Mockito for that. In latest versions it has Mockito.mockStatic() method. Here is an example

@Test
public void staticTest() {
    MockedStatic<GoogleDriveHelper> staticMock = Mockito.mockStatic(GoogleDriveHelper.class);
    staticMock.when(() -> GoogleDriveHelper.fixFileNameExtension(anyString(), anyString())).thenReturn("Blablabla");
    assertEquals("Blablabla", GoogleDriveHelper.fixFileNameExtension("abc", "bcd"));
}
Related