DEV Community

realNameHidden
realNameHidden

Posted on

2 1 1 1 1

when() method in Mockito example

Spring Boot example demonstrating the use of when() in unit testing with Mockito. The example covers a simple service and controller layer.

Scenario: Testing a Controller with Mocked Service Using when()

  1. Spring Boot Application Code Employee.java
package com.example.demo.model;

public class Employee {
    private String id;
    private String name;

    // Constructors, Getters, and Setters
    public Employee(String id, String name) {
        this.id = id;
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Enter fullscreen mode Exit fullscreen mode

EmployeeService.java

package com.example.demo.service;

import com.example.demo.model.Employee;
import org.springframework.stereotype.Service;

@Service
public class EmployeeService {
    public Employee getEmployeeById(String id) {
        // Simulate fetching employee from database
        return new Employee(id, "Default Name");
    }
}

Enter fullscreen mode Exit fullscreen mode

EmployeeController.java

package com.example.demo.controller;

import com.example.demo.model.Employee;
import com.example.demo.service.EmployeeService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class EmployeeController {
    private final EmployeeService employeeService;

    public EmployeeController(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    @GetMapping("/employees/{id}")
    public Employee getEmployee(@PathVariable String id) {
        return employeeService.getEmployeeById(id);
    }
}

Enter fullscreen mode Exit fullscreen mode
  1. Unit Test Using Mockito EmployeeControllerTest.java
package com.example.demo.controller;

import com.example.demo.model.Employee;
import com.example.demo.service.EmployeeService;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

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

class EmployeeControllerTest {

    @Mock
    private EmployeeService employeeService;

    @InjectMocks
    private EmployeeController employeeController;

    public EmployeeControllerTest() {
        MockitoAnnotations.openMocks(this); // Initialize mocks
    }

    @Test
    void testGetEmployee() {
        // Arrange: Mock the behavior of the service
        when(employeeService.getEmployeeById("1")).thenReturn(new Employee("1", "John Doe"));

        // Act: Call the controller method
        Employee employee = employeeController.getEmployee("1");

        // Assert: Verify the result
        assertNotNull(employee);
        assertEquals("1", employee.getId());
        assertEquals("John Doe", employee.getName());

        // Verify that the service method was called
        verify(employeeService, times(1)).getEmployeeById("1");
    }
}

Enter fullscreen mode Exit fullscreen mode

Explanation

@Mock:
The EmployeeService is mocked to simulate the behavior of fetching employee data.

@InjectMocks:
The EmployeeController uses the mocked EmployeeService.

when():
The when(employeeService.getEmployeeById("1")).thenReturn(...) statement stubs the behavior of getEmployeeById() to return a predefined employee object when invoked with "1".

assertEquals:
Used to verify that the response matches the expected values.

verify():
Ensures that getEmployeeById("1") was called exactly once.

Output

When running the test, it will:

Pass if the controller interacts correctly with the mocked service and returns the expected result.

Fail if:
The service is not called as expected.

The returned employee object doesn’t match the expected values.
Advantages of Using when()
Simulates service or repository behavior without actual database calls.

Allows testing specific scenarios like valid responses, exceptions, or empty results.

Decouples the test logic from the actual service implementation.
This approach ensures robust and isolated tests for your Spring Boot application’s layers.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay