Create a mocked list by mockito

后端 未结 3 688
花落未央
花落未央 2021-02-01 15:19

I want to create a mocked list to test below code:

 for (String history : list) {
        //code here
    }

Here is my implementation:

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-01 16:04

    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.

提交回复
热议问题