0

I have code something like this:

public void testMe(List<SomeItem> someList) {
  someList.forEach(someItem -> {
    SomeItem newItem = someService.createModifiedVersion(someItem);
    someService.doSomethingWith(newItem);
    someService.doMoreWith(newItem, someItem);
}

I am having hard time to write test with when and then verify as I have to mock createModifiedVersion with a loop. Right now I have something like this:

when(someService.createModifiedVersion(Mokito.any(SomeItem.class)))
  .thenReturn(someNewItem1)
  .thenReturn(someNewItem2)
  .thenReturn(someNewItem3);

Which doesn't ensure someNewItem<N> will be return for nth someItem from someItemList.

What will be best way to test in this case if I want to verify for all list items

verify(someService).doSomethingWith(someNewItem<N>);
verify(someService).doMoreWith(someNewItem<N>, oldItem<N>);

Note: represent nth element of the list

Any suggestion?

Update I guess I am asking how I can verify doMoreWith() is called with newItem and someItem as that is in loop.

Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
αƞjiβ
  • 3,056
  • 14
  • 58
  • 95
  • I don't quite understand your question. How do you work out which `someNewItem` you want to return, for each `SomeItem` that you pass? I feel sure the answer is to write an `Answer` implementation - I'm just not sure what that implementation would do. – Dawood ibn Kareem Apr 11 '17 at 23:08
  • @DavidWallace I have updated the sample code and my question. Hope that clarify the doubt I am having with mocking and testing within loop. – αƞjiβ Apr 12 '17 at 02:41
  • maybe something like: http://stackoverflow.com/questions/12166415/how-do-i-assert-an-iterable-contains-elements-with-a-certain-property – Jorge Campos Apr 12 '17 at 02:57
  • Take a look at Argument capture. As long as doMoreWith(....) is public method you must be able to mock & capture the arguments. You can also use doAnswer() API to capture the arguments, maintain state (collect the argument) and assert later. http://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#captors – Baski Apr 12 '17 at 06:50
  • Thanks for the responses .. but what about the `when` part how I can say for specific `someItem`it will return specific `newItem` – αƞjiβ Apr 12 '17 at 13:17
  • Yes, you can, using an `Answer` implementation. I can help you with this if you indicate exactly what you require the `Answer` implementation to do. Alternatively, you can just use a whole bunch of `when` statements, with a different `SomeItem` object passed to each one (so `when(someService.createModifiedVersion(someItem1).thenReturn(newItem1);` `when(someService.createModifiedVersion(someItem2).thenReturn(newItem2);` and so on. – Dawood ibn Kareem Apr 12 '17 at 19:41

0 Answers0