[Mockito] Mock List interface

Posted answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Mockito] Mock List interface相关的知识,希望对你有一定的参考价值。

In this post, we are going to see more functionalities in Mockito.

 

Mock a List interface:

    @Test
    public void testZie_returnOnce() {
        List listMock = mock(List.class);
        when(listMock.size()).thenReturn(10);
        assertEquals(10, listMock.size());
    }

 

Call multi times:

    @Test
    public void testZie_returnMultis() {
        List listMock = mock(List.class);
        when(listMock.size()).thenReturn(10).thenReturn(20);
        assertEquals(10, listMock.size());
        assertEquals(20, listMock.size());
    }

First call, return 10, second times return 20.

 

Mock, List.get():

    @Test
    public void testZie_returnGet() {
        List listMock = mock(List.class);
        when(listMock.get(0)).thenReturn("Good");
        assertEquals("Good", listMock.get(0));
        assertEquals(null, listMock.get(1));
    }

 

Mockito.anyInt():

    @Test
    public void testZie_returnGetAny() {
        List listMock = mock(List.class);
        when(listMock.get(Mockito.anyInt())).thenReturn("Good");
        assertEquals("Good", listMock.get(0));
        assertEquals("Good", listMock.get(1));
    }

 

以上是关于[Mockito] Mock List interface的主要内容,如果未能解决你的问题,请参考以下文章

Mockito.mock(SomeClass)和@Mock注释有什么区别?

Android单元测试系列-Mock之Mockito

单元测试(mock) 错误org.mockito.Mockito.framework()Lorg/mockito/MockitoFramework;解析

单元测试(mock) 错误org.mockito.Mockito.framework()Lorg/mockito/MockitoFramework;解析

Mock测试框架(Mockito为例)

Mockito - @Spy vs @Mock