Java PowerMock spy调用原始方法,但返回模拟值
我有以下方法,我模仿了私有方法Java PowerMock spy调用原始方法,但返回模拟值,java,mockito,powermockito,Java,Mockito,Powermockito,我有以下方法,我模仿了私有方法foo public class Foo { public int x; public void init() { x = foo(); } private int foo() { System.out.println("shouldn't print this"); return 11; } } 当我模仿该方法时,如下所示: @RunWith(Pow
foo
public class Foo {
public int x;
public void init() {
x = foo();
}
private int foo() {
System.out.println("shouldn't print this");
return 11;
}
}
当我模仿该方法时,如下所示:
@RunWith(PowerMockRunner.class)
@PrepareForTest({Main.class, Foo.class})
public class MainTest {
@Test
public void foo() throws Exception {
Foo f = PowerMockito.spy(new Foo());
PowerMockito.whenNew(Foo.class).withAnyArguments().thenReturn(f);
PowerMockito.when(f, "foo").thenReturn(42);
Main m = new Main();
m.f.init();
System.out.println(m.f.x);
}
}
它打印42而不是11,这是正确的,但它也打印不应打印此
是否可以在不调用私有方法的情况下模拟该方法?
不应打印此
正在打印,因为下面的行
PowerMockito.when(f, "foo").thenReturn(42);
相反,将行更改为
PowerMockito.doReturn(42).when(f,"foo");
不应打印此
由于以下行而被打印
PowerMockito.when(f, "foo").thenReturn(42);
相反,将行更改为
PowerMockito.doReturn(42).when(f,"foo");