简体   繁体   中英

Testing Multipartfile in spring boot Nullpointerexception due to MockMultipartFile

I have a controller that accepts a csv file and read information from file. The controller passes information to service layer to extract the required data.

The issue I am facing is when I upload a file using postman I get no issues. The information is read form file and all good. But when I am testing it I get NullPointerException. I have to prepare a test case where the whole controller has to be tested but I am stuck at the NullPointerException. I am not sure, but I think it is due to MockMultipartFile.

The controller is

@PostMapping("/validate-csv-file")
  public Flux<FormInstanceDTO> validateCsvFile(@RequestParam("file") MultipartFile file)
      throws Exception {
    if (file.isEmpty()) {
      return null;
    }

    String headerLine = fileValidationService.readHeaderOfFile(file); //  ***NULLPOINTERREXCEPTION*** 
   //this line passes information to service where i read the columns headers
   // above line is where test fails due to Nullpointerexception using MockMultipartFile. 
   //  But when I upload a csv file using postman, there is no error and the string headerline holds data
    String[] headerColumns = headerLine.split(",");

    String csvContent = fileValidationService.prepareDownloadCsvFile(file);

    Reader reader = new BufferedReader(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8));


    CsvToBean<ReferralCSV> csvToBean =
        new CsvToBeanBuilder(reader)
            .withType(ReferralCSV.class)
            .withIgnoreLeadingWhiteSpace(true)
            .build();

    List<ReferralCSV> referalCSVList = csvToBean.parse();


    Boolean passValidation = fileValidationService.validateReferral(referalCSVList);
    if (passValidation) {
      ReferralHeaderMetaData headerMetaData =
          fileValidationService.createHeaderMetaData(headerColumns);
      String clientCode = "123";
      FileValidationDTO dto = formService.getLatestFileValidationDTO(referralFormId, clientCode);
      //      dto.setHeaderMetaData(headerMetaData.toString());
      dto.setCsvContent(csvContent);
      Flux<FormInstanceDTO> formInstanceDTOFlux =
          formService.createFormInstance(referralFormId, dto);
      return formInstanceDTOFlux;
    }

    return null;


  }

and test is

@Test
  void status200WhenUploadingCSV() throws Exception {
    String path = String.valueOf(new ClassPathResource("referral-test.csv").getInputStream());
    ClassLoader classLoader = this.getClass().getClassLoader();
    File file = new File(classLoader.getResource("referral-test.csv").getFile());

   MockMultipartFile mockMultipartFile =
        new MockMultipartFile(
            "file",
            "referral-test.csv",
            "text/csv",
            new ClassPathResource("referral-test.csv").getInputStream());


    mockMvc
        .perform(MockMvcRequestBuilders.multipart("/rev/api/debt/v1/validate-csv-file/referral").file(mockMultipartFile))
        .andExpect(status().isOk());
  }

I do not have expertise in testing and spring boot and not sure how this will have to be solved.

Looking at the Unit test snippet, the service class and its behavior is not mocked. That should've resulted in NPE. Can you share stack trace if that's not the case? Cant figure out what caused NPE.

Here is an example of how to mock Mvc Controller

This one does multi part

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM