場景:模擬服務來測試控制器
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); } }
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中文網其他相關文章!