I\'m trying to mock private static method anotherMethod()
. See code below
public class Util {
public static String method(){
return
To to this, you can use PowerMockito.spy(...)
and PowerMockito.doReturn(...)
.
Moreover, you have to specify the PowerMock runner at your test class, and prepare the class for testing, as follows:
@PrepareForTest(Util.class)
@RunWith(PowerMockRunner.class)
public class UtilTest {
@Test
public void testMethod() throws Exception {
PowerMockito.spy(Util.class);
PowerMockito.doReturn("abc").when(Util.class, "anotherMethod");
String retrieved = Util.method();
Assert.assertNotNull(retrieved);
Assert.assertEquals(retrieved, "abc");
}
}
Hope it helps you.
If anotherMethod() takes any argument as anotherMethod(parameter), the correct invocation of the method will be:
PowerMockito.doReturn("abc").when(Util.class, "anotherMethod", parameter);
I'm not sure what version of PowerMock you are using, but with the later version, you should be using @RunWith(PowerMockRunner.class)
@PrepareForTest(Util.class)
Saying this, I find using PowerMock to be really problematic and a sure sign of a poor design. If you have the time/opportunity to change the design, I would try and do that first.