【发布时间】: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