英文:
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("不应打印这个");
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,这是正确的,但它也打印出了 不应打印这个
。
在没有调用该方法的情况下,是否有可能模拟私有方法?
英文:
I have following method which I mocked private method foo
.
public class Foo {
public int x;
public void init() {
x = foo();
}
private int foo() {
System.out.println("shouldn't print this");
return 11;
}
}
When I mocked the method as following:
@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);
}
}
It prints 42 instead of 11 which is correct but it also prints shouldn't print this
.
Is it possible to mock private method without having call to that method?
答案1
得分: 2
"shouldn't print this"之所以被打印出来,是因为下面这行代码。
PowerMockito.when(f, "foo").thenReturn(42);
相反,将这行代码修改为类似如下:
PowerMockito.doReturn(42).when(f, "foo");
英文:
shouldn' print this
is getting printed because of the below line.
PowerMockito.when(f, "foo").thenReturn(42);
Instead, change the line something like
PowerMockito.doReturn(42).when(f,"foo");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论