PowerMock间谍调用原始方法但返回模拟值

huangapple go评论70阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年9月29日 01:11:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/64106654.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定