首頁 >Java >java教程 >Mockito 範例中的 thenReturn() 方法

Mockito 範例中的 thenReturn() 方法

Mary-Kate Olsen
Mary-Kate Olsen原創
2025-01-27 00:07:07992瀏覽

thenReturn() method in Mockito example

場景:模擬服務來測試控制器

  1. 應用程式程式碼 員工.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 a 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. 使用 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");
    }
}

說明
when().thenReturn():

模擬employeeService.getEmployeeById("1")的行為,以在使用「1」呼叫時傳回特定的Employee物件。
依賴注入:

@Mock 建立 EmployeeService 的模擬。

@InjectMocks 將模擬 EmployeeService 注入 EmployeeController。

驗證:
verify(employeeService, times(1)).getEmployeeById("1") 確保模擬方法只被呼叫一次。

斷言:
根據預期值驗證傳回的 Employee 物件。

輸出
執行測試時:

它將呼叫控制器方法。

模擬的服務將傳回存根的 Employee 物件。
如果滿足以下條件,測試將通過:
傳回的 Employee 物件與預期值相符。

模擬的服務方法被呼叫了預期的次數。

這是在 Spring Boot 應用程式中使用 thenReturn() 來測試控制器邏輯的乾淨、實用的方法,而無需依賴實際的服務實作。

以上是Mockito 範例中的 thenReturn() 方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn