Spring 引导单元测试在返回硬编码值时无法正常工作

Spring boot unit test not not working while returning hard coded values

我有以下 REST 端点映射。

@GetMapping("/employee/{id}")
public ResponseEntity<Employee> getEmployee(@PathVariable("id") int id) {
    Employee employee = employeeRepository.getEmployeeById (id);
    if(employee == null) {
        throw new EmployeeNotFoundException ();
    }
    ResponseEntity<Employee> responseEntity = new ResponseEntity<Employee> (employee, HttpStatus.OK);
    return responseEntity;
}

为了测试失败路径,我有以下测试用例。

@Test
public void getEmployeeFailTest() throws Exception {
    Mockito.when (employeeRepository.getEmployeeById (Mockito.anyInt ())).thenReturn (null);
    RequestBuilder requestBuilder = MockMvcRequestBuilders.get ("/employee/10")
            .accept (MediaType.APPLICATION_JSON);
    MvcResult result = mockMvc.perform (requestBuilder).andReturn ();
    String response = result.getResponse ().getContentAsString ();
    System.out.println (employeeRepository.getEmployeeById (5)==null);
    String expected = "{\"errorCode\":1,\"message\":\"404: Employee not found!\"}";
    JSONAssert.assertEquals (expected, response, false);
    Assert.assertEquals (404, result.getResponse ().getStatus ());
}

在存储库 class 中,我正在 return 硬编码的 Employee 对象。

public Employee getEmployeeById(int i) {
    Employee employeeMock = new Employee (1, "XYZ","randomEmail@gmail.com",new Department (1, "HR"));
    return  employeeMock;
}

当我在上述方法中return null时,测试用例成功通过。但是通过上面的实现,它失败了。

感谢 Mockito.when (employeeRepository.getEmployeeById (Mockito.anyInt ())).thenReturn (null); getEmployeeById 在测试方法中 returning null 但在上面硬编码的控制器方法中 Employee 对象正在 returned

我是不是漏掉了什么?

您在 REST 控制器中的 employeeRepository 实例可能与您试图在测试中存根 return 值的实例不同。

对于大多数引用类型,模拟实例通常 return 默认为 null。由于您获得的是硬编码对象,因此看起来您的具体实现正在 REST 控制器中使用。 假设您的 REST 控制器通过某种依赖注入获得 employeeRepository,您需要确保将模拟注入其中,方法是显式注入它或为测试的 Spring 上下文提供模拟 bean。

1) 如果我正确理解了您的测试,那么您期望“404 not found”响应 "employee/10"。当你 return null 然后 REST 控制器抛出 EmployeeNotFoundException (我假设通过异常处理程序处理并转换为 404)。当您 return 非空对象时,不会抛出异常并且测试失败。

我建议您的存储库 class 模拟

找不到的对象
public Employee getEmployeeById(int i) {
  return i==10 ? null : new Employee (1, "XYZ","randomEmail@gmail.com",new Department (1, "HR"));
} 

2) Mockito.when (employeeRepository.getEmployeeById (Mockito.anyInt ())).thenReturn (null); 此代码似乎不起作用。我假设您没有正确地将 employeeRepository 注入 REST。您应该在测试 class 中用 @MockBean 标记它,这样 Spring 测试会比实际实现更喜欢它