In this post under Mockito, I will show how to create a mock of an interface with an example
Below is the complete example where I create a mock of java.util.List interface and call its method.
Test Class
1 package package3;
2
3 import static org.junit.Assert.assertEquals;
4 import static org.mockito.Mockito.when;
5
6 import java.util.List;
7
8 import org.junit.Test;
9 import org.mockito.Mockito;
10
11 public class ListTest {
12 @Test
13 public void testListAdd() {
14 List list = Mockito.mock(List.class);
15 when(list.get(0)).thenReturn(1);
16 when(list.get(1)).thenReturn(2);
17
18 assertEquals(1, list.get(0));
19 assertEquals(2, list.get(1));
20 }
21 }
In the above code, at line 14, we create a mock of List interface by calling Mockito class’s mock method.
In this way we can mock an interface.