2016-09-15 54 views
0

我有一個執行FileUpload的Spring控制器。我的控制器正在使用@RequestParam對多部分文件進行HTTP請求。我的問題是我不知道如何爲我的控制器編寫JUnit測試。我想傳入存儲在我的src/main/resources中的文件,並確保它處理並寫出內容。這裏是我的控制器編寫FileUpload的JUnit測試Spring MVC控制器

@RequestMapping(value = "/DefectImport", method = RequestMethod.POST) 
public @ResponseBody 

// Request file from upload explorer as a multipart file 
String uploadFileHandler(@RequestParam("file") MultipartFile file){ 
    //LOGGER.info(">>> uploadFileHandler started"); 

     // Check if file is multipart file 
     if (file.getContentType() != null) { 
      try { 

       Date uploadDate = new Date(); 
       //LOGGER.info(">>> Date: " + uploadDate); 
       System.out.println(uploadDate); 

       //Get input stream of the file 
       InputStream is = file.getInputStream(); 

       // Finds the workbook instance for XLSX file 
       XSSFWorkbook workbook = new XSSFWorkbook (is); 

       // Return first sheet from the XLSX workbook 
       XSSFSheet sheet = workbook.getSheetAt(0); 

       // Get iterator to all the rows in current sheet 
       Iterator<Row> ite = sheet.rowIterator(); 
       //LOGGER.info(">>> Writing Started of file " + file.getOriginalFilename()); 
       System.out.println("Writing Started of file " + file.getOriginalFilename()); 

       // Traversing over each row of XLSX file 
       while(ite.hasNext()){ 
        Row row = ite.next(); 

        // For each row, iterate through each column 
        Iterator<Cell> cite = row.cellIterator(); 
        while(cite.hasNext()){ 
         Cell c2 = cite.next(); 

         // Check for different data types and return value 
         switch (c2.getCellType()) { 
         case Cell.CELL_TYPE_STRING: 
          //LOGGER.info(c2.getStringCellValue() + " "); 
          System.out.print(c2.getStringCellValue() + " "); 
          break; 
         case Cell.CELL_TYPE_NUMERIC: 
          if (DateUtil.isCellDateFormatted(c2)) 
          { 
           SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); 
           //LOGGER.info(dateFormat.format(c2.getDateCellValue()) + " "); 
           System.out.print(dateFormat.format(c2.getDateCellValue()) + " "); 
          } 
          else 
          { 
           //LOGGER.info(c2.getNumericCellValue() + " "); 
           System.out.print(c2.getNumericCellValue() + " "); 
          }        
          break; 
         case Cell.CELL_TYPE_BOOLEAN: 
          //LOGGER.info(c2.getBooleanCellValue() + " "); 
          System.out.print(c2.getBooleanCellValue() + " "); 
          break; 
         default:        
         } 
        } 
        //LOGGER.debug(); 
        System.out.println(); 
       } 
       is.close(); 
       workbook.close(); 
       //LOGGER.info(">>> uploadFileHandler complete"); 
       System.out.println("Writing finished..."); 

      } 

      /** 
      * Error handling 
      */ 
      /*catch (InvalidFormatException e) 
      { 

      }*/ 
      catch (MaxUploadSizeExceededException e) 
      { 
       return "The file you uploaded is too large"; 
      } 
      catch (FileNotFoundException fe) 
      { 
       System.out.println("File not found"); 

      } 
      catch (IOException ie) 
      { 
       System.out.println("The file you uploaded is not an XLSX file"); 
      }  
     }   

     return "Thank you for your submission!"; 
    } 

} 

我該如何去寫一個測試用例?是否有可能做到這一點,而不使用模擬?我可以公開它作爲一個組件,並讓它接受來自請求參數的文件輸入流或文件嗎?

回答

0

您不需要測試文件的上傳。您可能想要測試的一點是控制器接收文件並正確處理文件。爲此,我建議從資源目錄中嘲笑和提供服務。

在編寫測試時,總是試着按照給定的時間,然後模型。例如:

@Test 
public void uploadFileTest() throws Exception{ 
    //given 
    InputStream uploadStream = UploadControllerTest.class.getClassLoader().getResourceAsStream("exceldocument.xlsx"); 
    MockMultipartFile file = new MockMultipartFile("file", uploadStream); 
    assert uploadStream != null; 

    //when 
    this.mockMvc.perform(fileUpload("/DefectImport") 
      .file(file)) 
    //then 
      .andExpect(status().isOk()); 
} 

這會嘲笑文件的分段上傳,並檢查InputStream是否爲空,且上傳狀態是否正常(200)。