Mockito when()

1. Overview

The when() method serves as a cornerstone for defining mock behaviors and establishing expectations for method calls. This tutorial will demonstrate the role of the when() method in Mockito, explaining its significance and practical use cases.

2. Development Steps

1. Initialize a Maven project.

2. Add the necessary dependencies (JUnit 5 and Mockito).

3. Sketch a class containing a method.

4. Construct a test class for the designed class.

5. Use the when() method to define mock behavior.

6. Create and execute test cases.

7. Inspect the test outputs.

3. Dependencies (Mockito and JUnit 5)

<!-- JUnit 5 -->
<!-- Mockito -->

4. Code Program

// Step 3: Develop the Service class
class WeatherService {
    String forecast(String city) {
        // In a real-world scenario, this might fetch weather data from an API
        return "Sunny";
// Step 4 and 5: Formulate a test class for WeatherService
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class WeatherServiceTest {
    public void forecastTest() {
        // Instantiate a mock of WeatherService
        WeatherService mockService = mock(WeatherService.class);
        // Define the mock behavior using when()
        // Invoke the mocked method
        String result = mockService.forecast("London");
        // Validate the result
        assertEquals("Rainy", result);


The forecastTest will succeed, proving that the when() method was aptly utilized to shape the behavior of the mocked WeatherService.

Code Explanation:

1. After integrating Mockito and JUnit 5, we crafted a simple WeatherService class possessing a forecast method. This method, in a real scenario, might interact with an external service to obtain weather data.

2. In our test suite, we spawned a mock of the WeatherService using Mockito's mock() method.

3. With this mock, we exploited the when() method to determine its behavior. Specifically, we specified that when the forecast method of our mock is called with "London" as the argument, it should return "Rainy".

4. Subsequent to this stubbing, we invoked the forecast method on our mock object and verified the returned value to ensure that our mock responded as defined.

5. Conclusion

Mockito's when() method plays a pivotal role in defining and customizing mock behavior. Its syntactic clarity and straightforwardness make stubbing a breeze. By mastering the use of when(), developers can construct robust unit tests that are both maintainable and lucid.

Related Mockito Methods

Mockito mock()
Mockito spy()
Mockito when()
Mockito thenThrow()
Mockito verify()
Mockito times()
Mockito never()
Mockito any()
Mockito eq()
Mockito inOrder()
Mockito doReturn()
Mockito doThrow()
Mockito doAnswer()
Mockito timeout()
Mockito ArgumentMatchers