PowerMock 间谍调用原始方法但 returns 模拟值
PowerMock spy calls original method but returns mocked value
我有以下方法,我模拟了私有方法 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,这是正确的,但它也打印 shouldn't print this
.
是否可以在不调用该方法的情况下模拟私有方法?
shouldn' print this
由于以下行而被打印出来。
PowerMockito.when(f, "foo").thenReturn(42);
相反,将行更改为
PowerMockito.doReturn(42).when(f,"foo");
我有以下方法,我模拟了私有方法 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,这是正确的,但它也打印 shouldn't print this
.
是否可以在不调用该方法的情况下模拟私有方法?
shouldn' print this
由于以下行而被打印出来。
PowerMockito.when(f, "foo").thenReturn(42);
相反,将行更改为
PowerMockito.doReturn(42).when(f,"foo");