@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());
}
}
@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();
}
}
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调试上面的测试case.debug指向不进入validationServiceImpl类。我想在验证Employee Object时抛出错误。如何在测试用例中处理异常。
答案 0 :(得分:0)
实际上你嘲笑ValidationService
依赖:
@MockBean
ValidationService validationService;
并且您没有指定模拟行为。因此,它允许在不抛出任何异常的情况下调用validatorService
依赖项。它的工作原理是validateEmp()
方法不能返回被测方法工作流所需的任何内容。
作为提醒,使用WebMvcTest
注释的测试旨在专注于控制器测试,而不是服务测试。
您可以删除@MockBean
注释以使validationService
成为真正的实现,而不是模拟:
ValidationService validationService;
但请注意,测试单一ValidationService
的更好方法是为它创建一个单元测试。
最后请注意,更好的方法是使用javax.validation
API来验证输入。
您可以在Employee类中进行注释,以在字段和控制器中定义约束,以验证参数,例如:
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();
}