鉴于类import AppTest from "./AppTest";
具有以下SchedulerResource
方法和方法中使用的一堆常量,如何使用mockito为createSchedules
方法编写单元测试?
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);
}
?
答案 0 :(得分:1)
简单:传入null,然后为mockMvc
对象放下不同的规范,例如andExpect(status().isNotFound()
(或类似的东西)。
除此之外,您可以使用 verifyZeroInteractions() 之类的方法来确保没有调用过去那个模拟的服务对象。
从这个意义上来说,它与测试其他案例并没有多大区别:你退后一步,看看else分支中发生的所有事情,然后你想办法如何观察/验证他们。