Spring MVC 测试 - 将空值作为参数传递

Spring MVC Test - Passing null value as parameter

我有一个控制器,其中一种方法接受空值作为参数,但我在尝试测试时遇到错误:java.lang.IllegalArgumentException:'values' 不能空

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

测试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)));
...

如何测试将 null 传递给 get 方法?

不向 get 方法传递任何内容。

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