2
我似乎無法模擬使用powermock返回公共函數調用。NullPointerException在powermock中調用時方法
有人可以幫我嗎?
失敗的線是
PowerMockito.doReturn(aa).when(B.class, B.class.getDeclaredMethod("getA"));
when
」 方法
代碼內
具體:
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:
更改代碼下面的作品,但它迫使我不想
B bb = new B(3);
B bb1 = PowerMockito.spy(bb);
PowerMockito.doReturn(aa).when(bb1).getA();
A mockedA = bb1.getA();
快速注:該文檔的'時()'方法傑夫提供的是在這裏:http://docs.mockito.googlecode.com/hg/latest/org/mockito只需直接與間諜互動/stubbing/Stubber.html#when(T)。附註:我確信上面的內容是簡化發佈的,但沒有任何內容似乎要求PowerMockito超過普通的舊Mockito。 –
@Brian你是對的;我儘可能地複製了後記。這適用於'Mockito.spy(new B(3))'和'Mockito.doReturn(aa).when(bb).getA()'。 –
哎呀,對不起 - 我的意思是作爲對OP的發佈代碼的評論。 –