In the below code we are going to mock the List Interface and override the method behaviour of List Methods
Methods mocked

  1. get(index)
  2. size()
  3. exception

ListTest.java

package com.mugil.org;

import org.junit.Before;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertNotEquals;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.junit.Assert.assertEquals;

public class ListTest {
    List arrEmployee;

    @Before
    public void init(){
        arrEmployee = mock(List.class);
    }

    @Test
    public void ListMock_SizeMethod(){
        when(arrEmployee.size()).thenReturn(3);
        assertEquals(3, arrEmployee.size());
    }

    @Test
    public void ListMock_GetMethod(){
        when(arrEmployee.get(0)).thenReturn("Employee1");
        when(arrEmployee.get(1)).thenReturn("Employee2");
        when(arrEmployee.get(2)).thenReturn("Employee3");

        assertEquals("Employee2", arrEmployee.get(1));
        assertNotEquals(null, arrEmployee.get(2));
    }

    @Test(expected = RuntimeException.class)
    public void ListMock_ThrowException(){
        when(arrEmployee.get(anyInt())).thenThrow(new RuntimeException());
        arrEmployee.get(1);
    }
}

Comments are closed.