我有一个带有以下语句的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?

最佳答案

在配置模拟时,您为其提供了一个故事板。您告诉它您希望从中采取什么行动。因此,您可以创建两个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);
    //...
  }
  //...
}

10-07 20:56