Cang Lu
Cang Lu

Reputation: 35

Unitest Create(Post) method using mockito

Given a class SchedulerResource which has the following createSchedules method and a bunch of constants used in the method, how can I use mockito to write a unit-test for the createSchedules method?

@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 class:

@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!")));        
}

So is ok with :

if(schedulerDTO != null)
{
  schedulerService.saveScheduler(schedulerDTO);
  customResponse.setMessage("Schedule has been created!");
  return new ResponseEntity<>(customResponse ,HttpStatus.OK);
}

But what about:

else{
  customResponse.setMessage("Not Create!");
  return new ResponseEntity<>(customResponse,HttpStatus.NOT_FOUND);   
}

So, - how can I write for the case where schedulerDTO == null?

Upvotes: 2

Views: 67

Answers (1)

GhostCat
GhostCat

Reputation: 140447

Simple: you pass in null, and then you put down different specs for your mockMvc object, such as andExpect(status().isNotFound() (or something alike).

Beyond that, you can use methods like verifyZeroInteractions() to ensure no calls went to that mocked service object for example.

In that sense, it really isn't much different from testing the other case: you step back, and look at all the things that happen in the else branch, and then you think of ways how to observe/verify them.

Upvotes: 1

Related Questions