Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java PowerMock spy调用原始方法,但返回模拟值_Java_Mockito_Powermockito - Fatal编程技术网

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");