Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Is it possible to mock a method with specific return values using Mockito's mock() method


Is it possible to mock a method with specific return values using Mockito's mock() method


Yes, it is possible to mock a method with specific return values using Mockito's `mock()` method. Mockito provides several ways to do this:

1. Using `when()` and `thenReturn()`:

java
   List<String> mockedList = Mockito.mock(List.class);
   when(mockedList.get(0)).thenReturn("mocked value");
   when(mockedList.get(1)).thenReturn("another mocked value");
   

In this example, we set up the mock to return specific values when the `get(0)` and `get(1)` methods are called.

2. Using `doReturn()` and `when()`:

java
   List<String> mockedList = Mockito.mock(List.class);
   doReturn("mocked value").when(mockedList).get(0);
   doReturn("another mocked value").when(mockedList).get(1);
   

This approach is an alternative way to set up the mock's behavior, using the `doReturn()` method instead of `thenReturn()`.

3. Using `thenAnswer()`:

java
   List<String> mockedList = Mockito.mock(List.class);
   when(mockedList.get(Mockito.anyInt())).thenAnswer(invocation -> "mocked value " + invocation.getArgument(0));
   

In this example, we use `thenAnswer()` to provide a dynamic response based on the argument passed to the `get()` method.

4. Using `thenThrow()`:

java
   List<String> mockedList = Mockito.mock(List.class);
   when(mockedList.get(0)).thenThrow(new RuntimeException("mocked exception"));
   

This allows you to set up the mock to throw a specific exception when the `get(0)` method is called.

5. Using `thenCallRealMethod()`:

java
   MyClass myClass = Mockito.spy(new MyClass());
   when(myClass.myMethod()).thenCallRealMethod();
   

In this case, we use `spy()` to create a partial mock, and then use `thenCallRealMethod()` to call the real implementation of the `myMethod()` method.

These examples demonstrate the various ways you can use Mockito's `mock()` method to set up specific return values or behaviors for the mocked methods. This allows you to control the behavior of the mock object and ensure that your tests are testing the desired functionality.

Remember that the choice of approach depends on the specific requirements of your test case and the behavior you want to simulate with the mock object.