[英]Spring Boot: file upload testing
我正在嘗試在 Spring REST 應用程序中創建單元測試。 該測試與 MultipartFile 上傳的端點有關。
這是我的方法在@RestController
接受的參數
@PostMapping("/upload")
public ResponseEntity uploadFile(@HasFileName @RequestParam("file") MultipartFile file,
@NotEmpty @RequestParam("entity") String entity, @NotEmpty @RequestParam("language") String language,
@NotEmpty @RequestParam("lastModified") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime lastModifiedDateTime,
@NotEmpty @RequestParam("createdDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime createdDateTime)
throws IOException {
我找不到從單元測試中的多部分獲取此信息的方法。 我找不到有關為 Spring REST 進行 Spring 單元測試的文檔,因此將不勝感激。
@Test
public void testUploadFile() throws Exception{
ResultMatcher ok = MockMvcResultMatchers.status().isOk();
String filename = "test.txt";
File file = new File("/test" + filename);
file.delete();
MockMultipartFile mockMultipartFile = new MockMultipartFile("file", "test.txt", "multipart/form-data", "test data".getBytes());
upload.uploadFile(mockMultipartFile, mockMultipartFile.getName()) //missing more data
//more logic on how to assert that the file is not empty
}
原則上,測試應該驗證 uploadFile 方法()的結果:
ResultActions result =
this.mockMvc.perform(multipart("/svc").file(file)
.header(HttpHeaders.AUTHORIZATION,
"Bearer token"))
.andExpect(content().string("response"))
.andExpect(status().isOk());
該文件是一個輸入參數,所以我不明白您為什么要驗證它不為空:我相信驗證與其他模擬的交互可能很有用(例如檢查文件是否在 FileService.save() 方法中使用)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.