我有一个关于在Sping Boot 中编写一个测试来上传Amazon S3中的图像的问题。
我试图编写它的测试方法,但我得到了如下所示的错误。
我该如何修复它?
下面是Rest控制器的方法
@RestController
@RequestMapping("/api/v1/bookImage")
@RequiredArgsConstructor
public class ImageRestController {
@PostMapping
public ResponseEntity<String> uploadImage(@RequestParam("bookId") Long bookId, @RequestParam("file") MultipartFile file) {
final String uploadImg = imageStoreService.uploadImg(convert(file), bookId);
service.saveImage(bookId, uploadImg);
return ResponseEntity.ok(uploadImg);
}
private File convert(final MultipartFile multipartFile) {
// convert multipartFile to File
File file = new File(Objects.requireNonNull(multipartFile.getOriginalFilename()));
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(multipartFile.getBytes());
return file;
} catch (IOException e) {
throw new RuntimeException("Failed to convert multipartFile to File");
}
}
下面是imageService的方法。
public String uploadImg(File file, Long bookId) {
s3amazon.putObject(BUCKET_NAME, bookId.toString(), file);
return baseUrl + bookId;
}
测试方法如下所示。
@Test
void itShouldGetImagePath_WhenValidBookIdAndFile() throws Exception{
// given - precondition or setup
String bookId = "1";
String imagePath = "amazon-imagepath";
String baseUrl = String.format(imagePath + "/%s", bookId);
Long bookIdValue = 1L;
MockMultipartFile uploadFile = new MockMultipartFile("file", new byte[1]);
// when - action or the behaviour that we are going test
when(imageStoreService.uploadImg(convert(uploadFile), bookIdValue)).thenReturn(baseUrl); -> HERE IS THE ERROR
// then - verify the output
mvc.perform(MockMvcRequestBuilders.multipart("/api/v1/bookImage")
.file(uploadFile)
.param("bookId", bookId))
.andExpect((ResultMatcher) content().string(baseUrl))
.andExpect(status().isOk());
}
private File convert(final MultipartFile multipartFile) {
// convert multipartFile to File
File file = new File(Objects.requireNonNull(multipartFile.getOriginalFilename()));
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(multipartFile.getBytes());
return file;
} catch (IOException e) {
throw new RuntimeException("Failed to convert multipartFile to File");
}
}
错误如下:Failed to convert multipartFile to File (java.lang.RuntimeException: Failed to convert multipartFile to Filejava.io.FileNotFoundException: )
我该如何修复它?
1条答案
按热度按时间pcrecxhr1#
解决方案如下所示。