【问题标题】:Spring boot unit test not not working while returning hard coded values返回硬编码值时 Spring Boot 单元测试不起作用
【发布时间】:2019-09-10 13:51:22
【问题描述】:

我有以下 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 对象被返回

我错过了什么吗?

【问题讨论】:

  • 显示您如何声明存储库。也只是为了清楚.. 你期望 null 但你得到一个硬编码的值对吗?

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


【解决方案1】:

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

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

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 会更喜欢它而不是真正的实现

【讨论】:

  • @Mock 没有注入任何东西,它是非常无用的注释。它所做的只是调用 Mockito.create 并分配给该字段。真正的实现由 Spring 注入,因为没有其他候选者。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-20
    • 2017-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 2016-11-25
    相关资源
    最近更新 更多