シナリオ:コントローラーをテストするためにサービスをock笑する
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; } }
employeService.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():
employeeRervice.getEmployeEByID( "1")の動作をmocksして、「1」で呼び出されたときに特定の従業員オブジェクトを返すようにします。
依存関係注射:
@InjectMocksは、employeeControllerに模擬従業員サービスを注入します
検証:Verify(employeService、times(1))。getemployeebyid( "1")モックされたメソッドが正確に1回呼び出されたことを確認します。
アサーション:
返された従業員オブジェクトを期待値に対して検証します
output
コントローラーメソッドを呼び出します
テストは以下の場合に渡されます
返された従業員オブジェクトは、期待値と一致します
ockedされたサービス方法は、予想される回数と呼ばれていました。
以上がMockito の例の thenReturn() メソッドの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。