我有一个带有以下语句的Java方法:
public void someMethod() {
.....
Long firstVal = someService.getSomeObject().getId();
Long secondVal = someService.getSomeObject().getNextFunc().getOtherObject().getId();
.....
}
现在我正在尝试测试此方法,并在模拟设置中尝试执行:
@RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest {
@Mock SomeService mockSomeService;
SomeObject someObject = new SomeObject();
@Before
public void setup() {
someObject.setId(123456);
when(mockSomeService.getSomeObject).thenReturn(someObject);
//...
}
//...
}
现在我该如何模拟secondVal?
答案 0 :(得分:1)
配置模拟时,您可以提供(让我们说)故事板。你告诉它你对它的期望是什么。因此,您可以创建两个SomeObject实例并配置对不同方法的调用。如果它是相同的方法,它甚至可以工作。
我改变你的代码:
SomeObject someObject1 = new SomeObject();
SomeObject someObject2 = new SomeObject();
@Before
public void setup() {
someObject1.setId(123456);
someObject2.setId(123457);
when(mockSomeService.getSomeObject).thenReturn(someObject1);
when(mockSomeService.getSomeObject.getNextFunc.getOtherObject).thenReturn(someObject2);
//...
}
//...
}