Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 855
αƞjiβ Avatar asked Dec 22 '25 08:12

αƞjiβ


1 Answers

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);
    //...
  }
  //...
}
like image 68
Peter Paul Kiefer Avatar answered Dec 23 '25 22:12

Peter Paul Kiefer