After exploring a real-life use case with Mockito, let’s now dive deeper into how the framework works by experimenting with one of Java’s core interfaces — List
.
In this tutorial, we’ll:
- Create a mock of the
List
interface - Stub methods to return fixed and multiple values
- Work with methods that accept parameters
Let’s get started.
1. Setting Up a Basic Mockito Test
We’ll start by mocking a simple List
object without using @RunWith
or @ExtendWith
. This keeps our example lightweight and focused.
Example: Mocking a List and Stubbing a Method
import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; import java.util.List; import org.junit.Test; import org.mockito.Mockito; public class ListMockTest { @Test public void testListSizeReturnsFixedValue() { List mockList = mock(List.class); when(mockList.size()).thenReturn(5); assertEquals(5, mockList.size()); } }
2. Returning Multiple Values on Consecutive Calls
Mockito allows us to stub a method to return different values on each call:
@Test public void testListSizeReturnsMultipleValues() { List mockList = mock(List.class); when(mockList.size()).thenReturn(5).thenReturn(10); assertEquals(5, mockList.size()); // First call assertEquals(10, mockList.size()); // Second call }
Explanation:
- The first call to
size()
returns 5. - The second call returns 10.
- If called more than twice, the last value is reused.
3. Stubbing Methods with Parameters
You can also stub methods that accept arguments. Here’s how to return a value when a specific parameter is passed:
@Test public void testListGetWithParameter() { List mockList = mock(List.class); when(mockList.get(0)).thenReturn("hello"); assertEquals("hello", mockList.get(0)); assertEquals(null, mockList.get(1)); // Returns null since not stubbed }
Explanation:
get(0)
returns “in28Minutes”.get(1)
is not stubbed, so it returns the default value, which isnull
.
4. Summary of Key Learnings
- We mocked the
List
interface usingMockito.mock()
. - We used
when(...).thenReturn(...)
to define stubbed behavior. - We saw how to return different values on subsequent method calls.
- We learned that unmocked method calls return default values (e.g.,
null
).
Mockito is very powerful and offers a lot of flexibility for stubbing behaviors. These basics will help you better understand how mocking works, especially with interfaces like List
that are common in real-world applications.