How To Handle Exception in Test Case
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | @RunWith(SpringRunner.class) @WebMvcTest(MyController.class) @ContextConfiguration(classes = Application.class) public class MyControllerTest { @Autowired MockMvc mockMvc; @MockBean EmployeeService employeeService; @MockBean EmployeeRepo employeeRepo; @MockBean ValidationService validationService; @Before public void setup(){ emp=new Employee(); objectMapper=new ObjectMapper(); emp.setId("123"); emp.setAge(100); emp.setName("pasam"); System.out.println("Employee object before Test"+emp); } @Test public void createEmp() throws Exception{ mockMvc.perform(MockMvcRequestBuilders.post("/sample/insert") .accept(MediaType.APPLICATION_JSON_VALUE) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(objectMapper.writeValueAsString(emp))).andExpect(status().isOk()).andDo(print()); } |
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | @RestController @RequestMapping("/sample") public class MyController { @Autowired private EmployeeService employeeService; @Autowired private ValidationService validationService; @PostMapping(value ="/insert",consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity insertEmployee(@RequestBody Employee employee){ validationService.validateEmp(employee); employeeService.create(employee); return ResponseEntity.ok().build(); } |
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public interface ValidationService { void validateEmp(Employee employee) ; } @Slf4j @Service public class ValidateServiceImpl implements ValidationService { @Override public void validateEmp(Employee employee) { if(employee.getAge()!=0){ log.info("Age can not be 0"); } } |
}
我正在尝试使用Spring Runner为Spring启动控制器编写测试用例,在我的控制器中我想验证员工对象,因为我已经编写了Validate Service接口.Above测试用例通过验证employee.while调试上面的测试用例.debug 指向不进入validationServiceImpl类。我想在验证Employee Object时抛出错误。如何在测试用例中处理异常。
实际上你嘲笑
1 2 | @MockBean ValidationService validationService; |
并且您没有指定模拟行为。 因此,它允许在不抛出任何异常的情况下调用
作为提醒,使用
您可以删除
1 | ValidationService validationService; |
但请注意,测试单一的
最后请注意,更好的方法是使用
您可以在Employee类中进行注释,以在字段和控制器中定义约束,以验证参数,例如:
1 2 3 4 5 6 7 8 | import javax.validation.Valid; ... @PostMapping(value ="/insert",consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity insertEmployee(@Valid @RequestBody Employee employe){ // validationService.validateEmp(employee); // Not required any longer employeeService.create(employee); return ResponseEntity.ok().build(); } |