I want to create a mocked list to test below code:
for (String history : list) {
//code here
}
Here is my implementation:
OK, this is a bad thing to be doing. Don't mock a list; instead, mock the individual objects inside the list. See Mockito: mocking an arraylist that will be looped in a for loop for how to do this.
Also, why are you using PowerMock? You don't seem to be doing anything that requires PowerMock.
But the real cause of your problem is that you are using when
on two different objects, before you complete the stubbing. When you call when
, and provide the method call that you are trying to stub, then the very next thing you do in either Mockito OR PowerMock is to specify what happens when that method is called - that is, to do the thenReturn
part. Each call to when
must be followed by one and only one call to thenReturn
, before you do any more calls to when
. You made two calls to when
without calling thenReturn
- that's your error.