You can do this using powermockito as shown below:
Say this is your class with a static method:
public final class MyStaticClass {
public static String helloWorld() {
return "Hello World";
}
}
helloWorld "Hi World" . :
@RunWith(PowerMockRunner.class)
@PrepareForTest({MyStaticClass.class})
public class PowerMockItoTest {
@Test
public void mockStaticClassTest() {
PowerMockito.mockStatic(MyStaticClass.class);
final String mockedResult = "Hi World";
Mockito.when(MyStaticClass.helloWorld()).thenReturn(mockedResult);
Assert.assertEquals(AStaticClass.helloWorld(), mockedResult);
}
}
PowerMock, , :
@RunWith(PowerMockRunner.class)
@PrepareForTest({MyStaticClass.class})
public class PowerMockTest {
@Test
public void testRegisterService() throws Exception {
PowerMock.mockStatic(MyStaticClass.class);
final String mockedResult = "Hi World";
expect(MyStaticClass.helloWorld()).andReturn(mockedResult);
replay(MyStaticClass.class);
Assert.assertEquals(AStaticClass.helloWorld(), mockedResult);
verify(MyStaticClass.class);
}
}