When stubbing with Mockito, we ofen specify a concrete argument for a method. After that, we can call the stubbed method with the same argument. For example, in the following code, the get() is stubbed with an argument of 0. So, when calling get(), the argument of get() is also 0. As such, the get() will return a integer, that is 3.
@RunWith(MockitoJUnitRunner.class)
public class MockitoTest {
@Mock
private List<Integer> mockedList;
@Test
public void test() {
when(mockedList.get(0)).thenReturn(3);
int element = mockedList.get(0);
assertEquals(3, element);
}
}
If the calling statement is modified as such:
int element = mockedList.get(1);
That is the argument is changed to 1, then Mockito throw 'NullPointerException', rather than a 'AssertionError'。 where is the null pointer?
And if we consider a case of throwing an exception rather than returning a value, the situation is more interesting. As the following code shows, though the two arguments of get() are different, a 'AssertionError' is thrown rather than a 'NullPointerException'.
@Test(expected = IndexOutOfBoundsException.class)
public void test() {
when(mockedList.get(0)).thenThrow(new IndexOutOfBoundsException());
mockedList.get(1);
}
It seems that when arguments are different, Mockito has different behaviors.