Mockito:嘲笑一个将在for循环中循环的arraylist

Reb*_*mes 21 java unit-testing mockito

我有一个测试方法,其中包含以下代码段:

private void buildChainCode(List<TracedPath> lines){
    for(TracedPath path : lines){
        /.../
    }
}
Run Code Online (Sandbox Code Playgroud)

我的单元测试代码如下所示:

public class ChainCodeUnitTest extends TestCase {

    private @Mock List<TracedPath> listOfPaths;
    private @Mock TracedPath tracedPath;

    protected void setUp() throws Exception {
        super.setUp();
        MockitoAnnotations.initMocks(this);
    }

    public void testGetCode() {
        when(listOfPaths.get(anyInt())).thenReturn(tracedPath);

        ChainCode cc = new ChainCode();
        cc.getCode(listOfPaths);

        /.../
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是,在运行测试时,测试代码永远不会进入for循环.什么时候我应该指定条件,以便输入for循环?目前我已指定when(listOfPaths.get(anyInt())).thenReturn(tracedPath),但我想它从未使用过.

Daw*_*ica 57

您的问题是,当您在for-each循环中使用集合时,iterator()会调用其方法; 而且你还没有找到那个特定的方法.

我没有嘲笑列表,而是强烈建议您只需传递一个真实的列表,其中的元素只是您的嘲笑TracedPath,可以根据需要多次传递.就像是

listOfPaths = Arrays.asList(mockTracedPath, mockTracedPath, mockTracedPath);
Run Code Online (Sandbox Code Playgroud)

  • 然后必须将 listOfPaths 显式设置为被测类,并且不能使用 @Mock 进行注释。 (2认同)

Chr*_*tle 6

在Java的for-each您的内部使用循环buildChainCode方法没有要求get(),因为你已经想通了-它的使用iterator()中定义的方法Collection<E>,其中List<E>延伸.

真的不建议嘲笑这个清单.它没有任何优势,除非您绝对必须检查列表是否经过迭代,即使这样,最好在给定某些输入的情况下断言或验证类的行为结果.

通过一些实施List<E>喜欢LinkedList<E>tracedPath它.