如何模拟其实例作为参数传递的类的非静态方法?

时间:2017-12-08 17:26:20

标签: java mocking junit4 powermockito

如何模拟传递给方法的参数类的非静态方法? 我正在测试以下方法:

public Seed getAppleSeed(AppleTree appleTree){
    Seed appleSeed = appleTree.getApple().getSeed();
    //Some logic flow
}

其他课程如下:

public class AppleTree{
    public Apple getApple(){
        return new Apple():
    }
}

public class Apple{
    public Seed getSeed(){
        return new Seed():
    }
}

最终目标是测试getAppleSeed()方法的流程,我需要模拟对getApple和getSeed的调用。

由于

1 个答案:

答案 0 :(得分:0)

嘲笑,像这样:

AppleTree appleTree = Mockito.mock(AppleTree.class);
Apple apple = Mockito.mock(Apple.class);

Seed seed  = new Seed();

Mockito.when(appleTree.getApple()).thenReturn(apple);
Mockito.when(apple.getSeed()).thenReturn(seed);

Seed actual = getAppleSeed(appleTree);

assertThat(actual, is(seed));

虽然如果实际代码与您在问题中列出的内容一样简单,那么我建议您无需模仿AppleAppleTree