返回硬编码值时,Spring Boot单元测试不起作用

时间:2019-04-20 17:59:44

标签: java spring-boot junit mockito spring-test

我具有以下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 ());
}

在存储库类中,我返回了硬编码的Employee对象。

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

当我以上述方法返回null时,测试用例成功通过。但是通过上述实现,它就会失败。

感谢Mockito.when (employeeRepository.getEmployeeById (Mockito.anyInt ())).thenReturn (null); getEmployeeById在测试方法中返回了null,但是在上面的硬编码Employee对象的控制器方法中却返回了

我想念什么吗?

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

1)如果我正确理解您的考试,那么您期望“ employee / 10”响应为“ 404 not found”。当您返回null时,REST控制器将抛出EmployeeNotFoundException(我认为这是通过异常处理程序处理的,并转换为404)。当您返回非null对象时,不会引发异常并且测试失败。

我建议您的存储库类模拟找不到的对象

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中。您应该在测试类中将其标记为@MockBean,以便Spring Test优先于实际实现使用它