0
@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 启动控制器编写测试用例,在我的控制器中我想验证员工对象,因为我已经编写了验证服务接口。上面的测试用例通过了验证员工。同时在上面调试测试用例。调试点不进入validationServiceImpl类。我想在验证员工对象时抛出错误。如何在测试用例中处理异常。

4

1 回答 1

0

实际上,您模拟了ValidationService依赖项:

@MockBean
ValidationService validationService;

并且您没有指定任何模拟行为。所以它允许在validatorService 不抛出任何异常的情况下调用依赖项。它的工作原理是该validateEmp()方法并非旨在返回被测方法的工作流程所需的任何内容。

As reminder, a test annotated with WebMvcTest is designed to focus on the controller testing, not the service testing.
You could remove the @MockBean annotation to make validationService the real implementation and not a mock :

ValidationService validationService;

But note that a better way to test unitary the ValidationService is creating a unit test for it.

At last note also that a still better way would be to use the javax.validation API to valid the input.
You could annotation in the Employee class to define the constraints on the fields and in the controller to validate the parameter such as :

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();    
 }
于 2018-04-29T08:00:31.617 回答