I want to test the PostMapping of my controller. It should receive a multipartfile and 2 boolean parameters, and return a response as an InputStreamRessource (I used this as it is easy with Spring). Therefore, I want to mock the beans (services). However, it seems that even though the service is correctly called, the output is always null.
Here is my controller:
@PostMapping(value = "/file",
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
produces = MediaType.TEXT_HTML_VALUE)
public ResponseEntity<InputStreamResource> parseMultipartFile(
@RequestParam MultipartFile multipartFile,
@RequestParam boolean hasOnlyOneSheet,
@RequestParam boolean hasBorders) throws IOException {
String fileContentType = multipartFile.getContentType();
if (mimeType.contains(fileContentType)) {
// Call service
InputStream parsedFile = multipartFileToHtmlService.multipartFileToHtml(multipartFile, hasOnlyOneSheet, hasBorders);
// Convert the result as InputStreamRessource to return
InputStreamResource inputStreamResource = new InputStreamResource(parsedFile);
return ResponseEntity.ok(inputStreamResource);
} else {
throw new UnsupportedImportMediaTypeException("Wrong file type;\n Import .xls or .xlsx file");
}
}
And the corresponding test Class:
@WebMvcTest
@RunWith(SpringRunner.class)
class HtmlExporterControllerTest {
@MockBean
MultipartFileToHtmlService multipartFileToHtmlService;
@MockBean
BeanFactory beanFactory;
@Autowired
MockMvc mockMvc;
@Test
public void parseMultipartFile_Should_Return_Ok() throws Exception {
MockMultipartFile mockMultipartFile = new MockMultipartFile(
"multipartFile",
"test.xls",
"application/xls",
"Hello World!".getBytes());
mockMvc.perform(multipart("/file").file(mockMultipartFile)
.param("hasOnlyOneSheet", "true")
.param("hasBorders", "true"))
.andExpect(status().isOk())
.andReturn();
}
}
For better explanation, here is a screenshot of my debug session while running the test:
As you can see, parsedFile is always null, I don't know why.
I also want to precise that it is working during manual testing, I do get the expected output, I just can't find a way to UnitTest my controller.
Aucun commentaire:
Enregistrer un commentaire