저번에 이어서 Image를 저장하는 ImageStore라는 서비스를 구현하고 api를 테스트해봤다.
public interface ImageStore {
public List<ImageUpload> store(List<MultipartFile> multipartFiles) throws IOException;
}
@Component
@RequiredArgsConstructor
public class ImageStorePC implements ImageStore{
private final ImageUploadRepository imageUploadRepository;
@Value("${file.dir}")
private String fileDir;
private String getFullPath(String filename) {
return fileDir + filename;
}
@Override
public List<ImageUpload> store(List<MultipartFile> multipartFiles) throws IOException {
if( multipartFiles.isEmpty()) {
return null;
}
List<ImageUpload> storeImageList = new ArrayList<>();
for (MultipartFile multipartFile : multipartFiles) {
if( !multipartFile.isEmpty()){
ImageUpload imageUpload = ImageUpload.createImageUpload(multipartFile);
multipartFile.transferTo(new File(getFullPath(imageUpload.getStorageImageName())));
storeImageList.add(imageUpload);
}
}
imageUploadRepository.saveAll(storeImageList);
return storeImageList;
}
}
@Controller
@RequiredArgsConstructor
public class PostController {
private final PostService postService;
@PostMapping("/posts/new")
public String savePost(@ModelAttribute PostForm postForm, RedirectAttributes redirectAttributes) throws IOException {
Long postId = postService.postSave(postForm.getImageFiles(), postForm.getContent());
redirectAttributes.addAttribute("postId", postId);
return "redirect:/post/{postId}";
}
...
}
@SpringBootTest
@AutoConfigureMockMvc
class PostControllerTest {
@Autowired
MockMvc mvc;
@Test
void 이미지업로드와_함께_포스트생성() throws Exception {
List<MultipartFile> multipartFileList = List.of(
new MockMultipartFile("image", "404.png", "image/png",
new FileInputStream(getClass().getResource("/img/404.png").getFile())),
new MockMultipartFile("image2","raspberry.png", "image/png",
new FileInputStream(getClass().getResource("/img/raspberry.png").getFile()))
);
mvc.perform(multipart("/posts/new")
.file("imageFiles", multipartFileList.get(0).getBytes())
.file("imageFiles", multipartFileList.get(1).getBytes())
.param("content", "test content"))
.andExpect(status().is3xxRedirection());
}
}
아쉬운 점
더 좋은 테스트 코드를 위해
Mockito에 대해서 더 공부해야겠다...