Mocking an interface

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;
3  import static org.junit.Assert.assertEquals;
4  import static org.mockito.Mockito.when;
6  import java.util.List;
8  import org.junit.Test;
9  import org.mockito.Mockito;
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);
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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s