You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
What if we combine a matcher with hardcoded value when stubbing.
Mock a few other List Methods.
What happens if an unstubbed method is called?
By default, for all methods that return a value, a mock will return either null, a a primitive/primitive wrapper value, or an empty collection, as appropriate. For example 0 for an int/Integer and false for a boolean/Boolean.
package com.in28minutes.data.api;
import java.util.List;
// External Service - Lets say this comes from WunderList
public interface TodoService {
public List<String> retrieveTodos(String user);
}
package com.in28minutes.mockito;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.mock;
import java.util.List;
import org.junit.Test;
import org.mockito.Mockito;
public class ListTest {
@Test
public void letsMockListSize() {
List list = mock(List.class);
Mockito.when(list.size()).thenReturn(10);
assertEquals(10, list.size());
}
@Test
public void letsMockListSizeWithMultipleReturnValues() {
List list = mock(List.class);
Mockito.when(list.size()).thenReturn(10).thenReturn(20);
assertEquals(10, list.size()); // First Call
assertEquals(20, list.size()); // Second Call
}
@Test
public void letsMockListGet() {
List<String> list = mock(List.class);
Mockito.when(list.get(0)).thenReturn("in28Minutes");
assertEquals("in28Minutes", list.get(0));
assertNull(list.get(1));
}
@Test
public void letsMockListGetWithAny() {
List<String> list = mock(List.class);
Mockito.when(list.get(Mockito.anyInt())).thenReturn("in28Minutes");
// If you are using argument matchers, all arguments
// have to be provided by matchers.
assertEquals("in28Minutes", list.get(0));
assertEquals("in28Minutes", list.get(1));
}
}