如何模拟实例作为参数传递的 class 的非静态方法?
How to mock a non static method of a class whose instance is passed as argument?
如何模拟传递给方法的参数 class 的非静态方法?
我正在测试以下方法:
public Seed getAppleSeed(AppleTree appleTree){
Seed appleSeed = appleTree.getApple().getSeed();
//Some logic flow
}
其余 class 如下:
public class AppleTree{
public Apple getApple(){
return new Apple():
}
}
public class Apple{
public Seed getSeed(){
return new Seed():
}
}
最终目标是测试 getAppleSeed() 方法的流程,为此我需要模拟对 getApple 和 getSeed 的调用。
谢谢
用 mocking,像这样:
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));
尽管如果实际代码与您在问题中概述的一样简单,那么我建议您无需模拟 Apple
或 AppleTree
。
如何模拟传递给方法的参数 class 的非静态方法? 我正在测试以下方法:
public Seed getAppleSeed(AppleTree appleTree){
Seed appleSeed = appleTree.getApple().getSeed();
//Some logic flow
}
其余 class 如下:
public class AppleTree{
public Apple getApple(){
return new Apple():
}
}
public class Apple{
public Seed getSeed(){
return new Seed():
}
}
最终目标是测试 getAppleSeed() 方法的流程,为此我需要模拟对 getApple 和 getSeed 的调用。
谢谢
用 mocking,像这样:
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));
尽管如果实际代码与您在问题中概述的一样简单,那么我建议您无需模拟 Apple
或 AppleTree
。