I can’t seem to mock the return of a public function call using powermock.
Can someone please help me?
The failing line is
PowerMockito.doReturn(aa).when(B.class, B.class.getDeclaredMethod("getA"));
specifically inside the “when” method
Code:
import static org.junit.Assert.fail;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
public class PowermockTest {
private static class A {
private int number;
public A(int number) {
this.number = number;
}
public int getNumber() {
return number;
}
}
private static class B {
private int number;
private A a;
public B(int number) {
this.number = number;
}
public A getA() {
if (a == null) {
a = new A(number);
}
return a;
}
}
@Test
public void testOdrService() {
A aa = PowerMockito.mock(A.class);
try {
B bb = new B(3);
PowerMockito.doReturn(aa).when(B.class, B.class.getDeclaredMethod("getA"));
} catch (Exception e) {
fail("Exception in test. " + e.getMessage());
}
}
}
PS:
Changing the code to the following works but it is forcing the creation of a dummy object which i don’t want
B bb = new B(3);
B bb1 = PowerMockito.spy(bb);
PowerMockito.doReturn(aa).when(bb1).getA();
A mockedA = bb1.getA();
This syntax is specifically for mocking static methods, not mocking instance methods like
getA().In most situations, you should not need to keep the original (spied) object. Just interact with the spy directly: