Mockito (五)
Mockito mock 泛型类、泛型接口
示例:
import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import static org.mockito.Mockito.*; public class MockitoDemo { @Test public void test() { ArrayList<String> mockList = mock(ArrayList.class); // 这种写法不够精确,IDE也会警告 when(mockList.get(0)).thenReturn("abc"); Assert.assertEquals(3, mockList.get(0).length()); } }
下面这种用 @Mock 注解的方法,IDE 不会警告:
import org.junit.Assert; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.ArrayList; import static org.mockito.Mockito.*; public class MockitoDemo { @Mock private ArrayList<String> mockList; @Test public void test() { MockitoAnnotations.initMocks(this); when(mockList.get(0)).thenReturn("abc"); Assert.assertEquals(3, mockList.get(0).length()); } }
转载:https://www.letianbiji.com/java-mockito/mockito-mock-generic.html
带着疑问去思考,然后串联,进而归纳总结,不断追问自己,进行自我辩证,像侦查嫌疑案件一样看待技术问题,漆黑的街道,你我一起寻找线索,你就是技术界大侦探福尔摩斯