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() 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; } } 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"); } } 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); } } 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"); } } 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.

Jan 18, 2025 - 16:51
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;
    }
}

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");
    }
}

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);
    }
}

  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");
    }
}

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.