代码之家  ›  专栏  ›  技术社区  ›  Govinda Sakhare

返回硬编码值时,弹簧靴单元测试不工作

  •  0
  • Govinda Sakhare  · 技术社区  · 7 年前

    我有下面的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 ());
    }
    

    在repository类中,我将返回硬编码的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 正在回归 无效的 在测试方法中,但在控制器方法中 Employee 正在返回对象

    我遗漏了什么吗?

    0 回复  |  直到 7 年前
        1
  •  0
  •   Alexander Pavlov    7 年前

    1)如果我正确理解您的测试,那么您希望“Employee/10”响应“404 Not Found”。当你回来的时候 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 好好休息。你应该把它标上 @MockBean 在您的测试类中,因此spring测试将更喜欢它而不是真正的实现

        2
  •  0
  •   Tore Brandtzæg    7 年前

    rest控制器中的employeerepository实例可能与您试图在测试中存根返回值的实例不同。

    对于大多数引用类型,模拟实例通常默认返回null。因为您正在获取硬编码对象,所以看起来您的具体实现正在rest控制器中使用。 假设您的rest控制器通过某种依赖注入获得employeerepository,那么您需要确保您的mock被注入其中,或者显式地注入它,或者为测试的spring上下文提供一个mock bean。