0
0
JunitHow-ToBeginner ยท 4 min read

How to Use when thenReturn in Mockito with JUnit Tests

In JUnit tests, use Mockito's when() method to specify a method call on a mock object, followed by thenReturn() to define the value it should return. This helps simulate behavior of dependencies without running real code, making tests faster and isolated.
๐Ÿ“

Syntax

The basic syntax for mocking a method call with Mockito is:

  • when(mock.method(args)).thenReturn(value);

Here, mock is the mocked object, method(args) is the method call you want to mock, and value is what the method should return when called.

java
when(mockedList.get(0)).thenReturn("first element");
๐Ÿ’ป

Example

This example shows how to mock a List's get method to return a specific string using Mockito in a JUnit test.

java
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;

import java.util.List;

import org.junit.jupiter.api.Test;

public class MockitoWhenThenReturnTest {

    @Test
    public void testWhenThenReturn() {
        // Create mock
        List<String> mockedList = mock(List.class);

        // Define behavior
        when(mockedList.get(0)).thenReturn("first element");

        // Use mock
        String result = mockedList.get(0);

        // Verify
        assertEquals("first element", result);
    }
}
Output
Test passed
โš ๏ธ

Common Pitfalls

Common mistakes when using when().thenReturn() include:

  • Calling the real method instead of the mock method inside when(). Always pass a method call on the mock object.
  • Using thenReturn() with void methods (use doReturn() or doAnswer() instead).
  • Not initializing mocks properly, causing NullPointerException.

Example of wrong and right usage:

java
import static org.mockito.Mockito.*;

// Wrong: calling real method inside when()
// when(realObject.method()).thenReturn(value); // This calls the real method!

// Right: call method on mock
when(mockObject.method()).thenReturn(value);
๐Ÿ“Š

Quick Reference

UsageDescription
when(mock.method(args)).thenReturn(value);Mocks method call to return value
doReturn(value).when(mock).method(args);Alternative for void or spy methods
verify(mock).method(args);Verify method was called
mock(Class.class);Create mock object
โœ…

Key Takeaways

Use when(mock.method(args)).thenReturn(value) to mock method return values in JUnit tests.
Always call the method on the mock inside when(), never on a real object.
Use doReturn() for void methods or spies where when() does not work.
Initialize mocks properly to avoid NullPointerException.
Verify behavior with verify() to ensure methods were called as expected.