如果一个类SchedulerResource具有以下createSchedules方法和方法中使用的一组常量,那么如何使用mockito为createSchedules方法编写单元测试?
@PostMapping
public ResponseEntity<CustomResponse> createScheduler(@Valid @RequestBody SchedulerDTO schedulerDTO) {
if(schedulerDTO != null)
{
schedulerService.saveScheduler(schedulerDTO);
customResponse.setMessage("Schedule has been created!");
return new ResponseEntity<>(customResponse ,HttpStatus.OK);
} else {
customResponse.setMessage("Not Create!");
return new ResponseEntity<>(customResponse,HttpStatus.NOT_FOUND);
}
}考试班:
@Test
public void createScheduler_Success() throws Exception {
SchedulerDTO scheduler = new SchedulerDTO();
Long sId = new Long(2);
scheduler.setSchedulerId(sId);
scheduler.setLinearChannelId((long)1);
scheduler.setDurationMs((long) 5000);
scheduler.setStatus(StatusEnum.NEW);
scheduler.setStartTime("2018-03-01T05:55:25");
scheduler.setEndTime("2018-03-01T05:57:25");
when(schedulerService.saveScheduler(scheduler)).thenReturn(scheduler);
mockMvc.perform(post("/linear/api/1.0/schedules")
.contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(scheduler)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.message", is("Schedule has been created!")));
}因此,我们可以:
if(schedulerDTO != null)
{
schedulerService.saveScheduler(schedulerDTO);
customResponse.setMessage("Schedule has been created!");
return new ResponseEntity<>(customResponse ,HttpStatus.OK);
}但是,关于:
else{
customResponse.setMessage("Not Create!");
return new ResponseEntity<>(customResponse,HttpStatus.NOT_FOUND);
}所以,-我怎么写schedulerDTO == null的例子
发布于 2018-05-18 03:48:59
简单:传入null,然后为mockMvc对象设置不同的规范,比如andExpect(status().isNotFound() (或类似的东西)。
除此之外,您还可以使用像https://stackoverflow.com/questions/11936301/mockito-how-to-verify-that-a-mock-was-never-invoked这样的方法来确保没有调用该模拟的服务对象。
从这个意义上说,这与测试另一种情况并没有太大的不同:你后退一步,看看其他分支中发生的所有事情,然后想出如何观察/验证它们的方法。
https://stackoverflow.com/questions/50403402
复制相似问题