Create a mocked list by mockito

后端 未结 3 685
花落未央
花落未央 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:06

    We can mock list properly for foreach loop. Please find below code snippet and explanation.

    This is my actual class method where I want to create test case by mocking list. this.nameList is a list object.

    public void setOptions(){
        // ....
        for (String str : this.nameList) {
            str = "-"+str;
        }
        // ....
    }
    

    The foreach loop internally works on iterator, so here we crated mock of iterator. Mockito framework has facility to return pair of values on particular method call by using Mockito.when().thenReturn(), i.e. on hasNext() we pass 1st true and on second call false, so that our loop will continue only two times. On next() we just return actual return value.

    @Test
    public void testSetOptions(){
        // ...
        Iterator itr = Mockito.mock(Iterator.class);
        Mockito.when(itr.hasNext()).thenReturn(true, false);
        Mockito.when(itr.next()).thenReturn(Mockito.any(String.class);  
    
        List mockNameList = Mockito.mock(List.class);
        Mockito.when(mockNameList.iterator()).thenReturn(itr);
        // ...
    }
    

    In this way we can avoid sending actual list to test by using mock of list.

提交回复
热议问题