αƞjiβ
αƞjiβ

Reputation: 3266

Mock same statement twice

I have a Java method with the following statement:

public void someMethod() {
  .....
  Long firstVal = someService.getSomeObject().getId();
  Long secondVal = someService.getSomeObject().getNextFunc().getOtherObject().getId();
  .....
}

Now I am trying to test this method and in mock setup I am trying to do like:

@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);
    //...
  }
  //...
}

Now how can I mock for secondVal?

Upvotes: 3

Views: 175

Answers (1)

Peter Paul Kiefer
Peter Paul Kiefer

Reputation: 2134

When you configure the mock, you provide it with (let's say) a story board. You tell it which action you expect from it. So you can create two SomeObject instances and configure the calls to the different methods.That would even work if it would be the same method.

I change your code:

  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);
    //...
  }
  //...
}

Upvotes: 1

Related Questions