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

Mockito 範例中的 thenReturn() 方法

Jan 27, 2025 am 12:07 AM

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

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

Rimworld Odyssey溫度指南和Gravtech
1 個月前 By Jack chen
Rimworld Odyssey如何釣魚
1 個月前 By Jack chen
我可以有兩個支付帳戶嗎?
1 個月前 By 下次还敢
初學者的Rimworld指南:奧德賽
1 個月前 By Jack chen
PHP變量範圍解釋了
3 週前 By 百草

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Laravel 教程
1603
29
PHP教程
1508
276
Hashmap在Java內部如何工作? Hashmap在Java內部如何工作? Jul 15, 2025 am 03:10 AM

HashMap在Java中通過哈希表實現鍵值對存儲,其核心在於快速定位數據位置。 1.首先使用鍵的hashCode()方法生成哈希值,並通過位運算轉換為數組索引;2.不同對象可能產生相同哈希值,導致衝突,此時以鍊錶形式掛載節點,JDK8後鍊錶過長(默認長度8)則轉為紅黑樹提升效率;3.使用自定義類作鍵時必須重寫equals()和hashCode()方法;4.HashMap動態擴容,當元素數超過容量乘以負載因子(默認0.75)時,擴容並重新哈希;5.HashMap非線程安全,多線程下應使用Concu

如何處理Java中的字符編碼問題? 如何處理Java中的字符編碼問題? Jul 13, 2025 am 02:46 AM

處理Java中的字符編碼問題,關鍵是在每一步都明確指定使用的編碼。 1.讀寫文本時始終指定編碼,使用InputStreamReader和OutputStreamWriter並傳入明確的字符集,避免依賴系統默認編碼。 2.在網絡邊界處理字符串時確保兩端一致,設置正確的Content-Type頭並用庫顯式指定編碼。 3.謹慎使用String.getBytes()和newString(byte[]),應始終手動指定StandardCharsets.UTF_8以避免平台差異導致的數據損壞。總之,通過在每個階段

Java中的可比較與比較器 Java中的可比較與比較器 Jul 13, 2025 am 02:31 AM

在Java中,Comparable用於類內部定義默認排序規則,Comparator用於外部靈活定義多種排序邏輯。 1.Comparable是類自身實現的接口,通過重寫compareTo()方法定義自然順序,適用於類有固定、最常用的排序方式,如String或Integer。 2.Comparator是外部定義的函數式接口,通過compare()方法實現,適合同一類需要多種排序方式、無法修改類源碼或排序邏輯經常變化的情況。兩者區別在於Comparable只能定義一種排序邏輯且需修改類本身,而Compar

如何在Java的地圖上迭代? 如何在Java的地圖上迭代? Jul 13, 2025 am 02:54 AM

遍歷Java中的Map有三種常用方法:1.使用entrySet同時獲取鍵和值,適用於大多數場景;2.使用keySet或values分別遍歷鍵或值;3.使用Java8的forEach簡化代碼結構。 entrySet返回包含所有鍵值對的Set集合,每次循環獲取Map.Entry對象,適合頻繁訪問鍵和值的情況;若只需鍵或值,可分別調用keySet()或values(),也可在遍歷鍵時通過map.get(key)獲取值;Java8中可通過Lambda表達式使用forEach((key,value)-&gt

Java中的'靜態”關鍵字是什麼? Java中的'靜態”關鍵字是什麼? Jul 13, 2025 am 02:51 AM

InJava,thestatickeywordmeansamemberbelongstotheclassitself,nottoinstances.Staticvariablesaresharedacrossallinstancesandaccessedwithoutobjectcreation,usefulforglobaltrackingorconstants.Staticmethodsoperateattheclasslevel,cannotaccessnon-staticmembers,

如何在Windows中設置Java_home環境變量 如何在Windows中設置Java_home環境變量 Jul 18, 2025 am 04:05 AM

tosetjava_homeonwindows,firstLocateThejDkinStallationPath(例如,C:\ programFiles \ java \ jdk-17),tencreateasyemystemenvironmentvaria blenamedjava_homewiththatpath.next,updateThepathvariaby byadding%java \ _home%\ bin,andverifyTheSetupusingjava-versionAndjavac-v

如何使用JDBC處理Java的交易? 如何使用JDBC處理Java的交易? Aug 02, 2025 pm 12:29 PM

要正確處理JDBC事務,必須先關閉自動提交模式,再執行多個操作,最後根據結果提交或回滾;1.調用conn.setAutoCommit(false)以開始事務;2.執行多個SQL操作,如INSERT和UPDATE;3.若所有操作成功則調用conn.commit(),若發生異常則調用conn.rollback()確保數據一致性;同時應使用try-with-resources管理資源,妥善處理異常並關閉連接,避免連接洩漏;此外建議使用連接池、設置保存點實現部分回滾,並保持事務盡可能短以提升性能。

Java虛擬線程性能基準測試 Java虛擬線程性能基準測試 Jul 21, 2025 am 03:17 AM

虚拟线程在高并发、IO密集型场景下性能优势显著,但需注意测试方法与适用场景。1.正确测试应模拟真实业务尤其是IO阻塞场景,使用JMH或Gatling等工具对比平台线程;2.吞吐量差距明显,在10万并发请求下可高出几倍至十几倍,因其更轻量、调度高效;3.测试中需避免盲目追求高并发数,适配非阻塞IO模型,并关注延迟、GC等监控指标;4.实际应用中适用于Web后端、异步任务处理及大量并发IO场景,而CPU密集型任务仍适合平台线程或ForkJoinPool。

See all articles