I am trying to cover the catch blocks in the code below but I am unable to. I understand that I need to cause an IOException while reading/writing into a file but I am not able to. Also, I cannot use PowerMockito to cover static methods as I am using Junit5. Can anyone help?
@Override
public String execute(UploadCategoryImageCommandRequest request) {
File tempFile = null;
FileOutputStream fos = null;
String fileName = "";
fileName = UUID.randomUUID().toString() + System.currentTimeMillis() + ".svg";
try {
tempFile = File.createTempFile(fileName, "svg");
fos = new FileOutputStream(tempFile);
fos.write(request.getFile().getBytes());
} catch (IOException e) {
log.error("File Creation Error: {}", e);
upload.setFileStatus(FileStatus.FAILED);
uploadRepository.save(upload);
throw new ApplicationException(ErrorKey.IMAGE_UPLOAD, ErrorCode.FAILED);
}
return string;
}
This is one of the test case that i have written but it returns this error - org.mockito.exceptions.misusing.MissingMethodInvocationException: when() requires an argument which has to be 'a method call on a mock'. For example: when(mock.getArticles()).thenReturn(articles);
Also, I am not sure if I should mock the File class in the below test case that I have written
@Test
public void exception() throws IOException {
Upload upload = Upload.builder().fileStatus(FileStatus.FAILED).imagePath("http://").build();
MockMultipartFile firstFile = new MockMultipartFile("fileName", "fileName.svg", "text/plain", "some xml".getBytes());
UploadCategoryImageCommandRequest uploadCategoryImageCommandRequest = UploadCategoryImageCommandRequest.builder()
.file(firstFile)
.uploadType(UploadType.CATEGORY)
.build();
Mockito.when(file.createTempFile("filename","svg")).thenThrow(IOException.class);
uploadCategoryImageCommand.execute(uploadCategoryImageCommandRequest);
}