场景:模拟服务来测试控制器
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中文网其他相关文章!