Search code examples
spring-boot-testmockmvc

Spring MVC Test - Passing null value as parameter


I have a controller with one method that accept null values as parameter but I'm getting an error when I try to test: java.lang.IllegalArgumentException: 'values' must not be empty

@GetMapping("/search")
public ResponseEntity<List<ProductionCycleExecutionDTO>> search(@RequestParam(required = false) String countryId,
            @RequestParam(required = false) String yearMonth, @RequestParam(required = false) String status,
            @RequestParam(required = false) String name) {
    log.info("search");
...

Test class:

@Autowired
private MockMvc mvc;

@MockBean
private ProductionCycleExecutionService prodCycleExecService;

...

@Test
public void givenProdCycle_whenSearchByParams_thenReturnJsonOk() throws Exception {
    log.debug("Test givenProdCycle_whenSearchByParams_thenReturnJsonOk()");
    List<ProductionCycleExecutionDTO> listProdCycleExec = new ArrayList<>();

    ProductionCycleExecutionDTO productionCycleExecutionDTO = ProductionCycleExecutionDTO.builder().cycleId("1")
                .yearMonth("202005").name("Start_Cycle_TransferFile").status("AC").build();

    listProdCycleExec.add(productionCycleExecutionDTO);

    when(prodCycleExecService.searchByParams(null, null, null, null)).thenReturn(listProdCycleExec);

    mvc.perform(get("/production-cycle-execution/search").param("countryId", null).param("yearMonth", null)
                .param("status", null).param("name", null)).andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON)).andExpect(jsonPath("$", hasSize(1)));
...

How can I test passing null to the get method?


Solution

  • Only pass nothing to the get method.

    mvc.perform(get("/production-cycle-execution/search")).andExpect(status().isOk())
                    .andExpect(content().contentType(MediaType.APPLICATION_JSON)).andExpect(jsonPath("$", hasSize(1)));