给定一个 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
的情况编写代码?
最佳答案
简单:您传入 null,然后为您的 mockMvc
对象设置不同规范,例如 andExpect(status().isNotFound()
(或类似的东西)。
除此之外,您还可以使用 verifyZeroInteractions() 等方法 例如,确保没有调用转到那个模拟的服务对象。
从这个意义上说,它与测试另一种情况并没有太大区别:您退后一步,查看 else 分支中发生的所有事情,然后想办法观察/验证它们。
关于java - 使用 mockito 的 Unitest Create(Post) 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50403402/