DEV Community

realNameHidden
realNameHidden

Posted on

thenReturn() method in Mockito example

Scenario: Mocking a Service to Test a Controller

  1. 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 a 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 Code Using thenReturn() 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: Use when().thenReturn() to mock service behavior
        when(employeeService.getEmployeeById("1")).thenReturn(new Employee("1", "John Doe"));

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

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

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

Enter fullscreen mode Exit fullscreen mode

Explanation
when().thenReturn():

Mocks the behavior of employeeService.getEmployeeById("1") to return a specific Employee object when called with "1".
Dependency Injection:

@Mock creates a mock of the EmployeeService.

@InjectMocks injects the mock EmployeeService into the EmployeeController.

Verify:
verify(employeeService, times(1)).getEmployeeById("1") ensures the mocked method was called exactly once.

Assertion:
Validates the returned Employee object against expected values.

Output
When the test is executed:

It will call the controller method.

The mocked service will return the stubbed Employee object.
The test will pass if:
The returned Employee object matches the expected values.

The mocked service method was called the expected number of times.

This is a clean, practical way to use thenReturn() in a Spring Boot application to test controller logic without relying on the actual service implementation.

Top comments (0)