我正在尝试使用PowerMockito模拟私有方法。
示例代码如下。
理想情况下, m2()应该返回“来自间谍方法”。
不确定会丢失什么。
请澄清。
Sample.java
import java.io.IOException;
public class Sample {
public void m1(String input) throws IOException {
System.out.println("Sample.m1() BEGIN");
String r = m2(input);
System.out.println("Sample.m1() END--> " + r);
}
private String m2(String s) {
System.out.println("Sample.m2()" + s);
return "From m2 method";
}
}
SampleTest.java
import static org.mockito.Matchers.anyString;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Sample.class })
public class SampleTest {
@Test
public void testM1() throws Exception {
Sample spy = PowerMockito.spy(new Sample());
PowerMockito.doReturn("from spy method").when(spy, "m2", anyString());
Sample sample = new Sample();
sample.m1("Hi m1!!!");
}
}
输出
Sample.m1() BEGIN
Sample.m2()Hi m1!!!
Sample.m1() END--> From m2 method
答案 0 :(得分:0)
我需要在间谍实例而不是示例实例上调用m1()。 感谢Giacomo Alzetta的建议。
修改后的代码:
@Test
public void testM1() throws Exception {
Sample spy = PowerMockito.spy(new Sample());
PowerMockito.doReturn("from spy method").when(spy, "m2", anyString());
spy.m1("Hi m1!!!");
}