I have a working controller for uploading csv's in a post request. Status 200 in postman, status 400 while testing. I'm struggling to see what the problem is.
Controller:
@RestController
@RequestMapping("/csv")
public class CsvController {
final CsvService csvService;
public CsvController(CsvService csvService) {
this.csvService = csvService;
}
@PostMapping("/upload")
public ResponseEntity<Response> uploadFile(@RequestParam("file")MultipartFile file) {
if(CsvHelper.hasCSVFormat(file)) {
Response response = csvService.save(file);
return new ResponseEntity<>(response, HttpStatus.valueOf(response.getStatus()));
}
Response response = new Response().setStatus(400).setMessage("Please upload a CSV file");
return new ResponseEntity<>(response, HttpStatus.valueOf(response.getStatus()));
}
}
CsvHelper Util:
public class CsvHelper {
public static String TYPE = "text/csv";
public static boolean hasCSVFormat(MultipartFile file) {
return TYPE.equals(file.getContentType());
}
}
Test:
@ExtendWith(SpringExtension.class)
@WebMvcTest(value = CsvController.class)
public class TestControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private CsvService csvService;
@Test
void status200WhenUploadingCSV() throws Exception {
MockMultipartFile mockMultipartFile = new MockMultipartFile(
"multipartFile",
"template.csv",
"text/csv",
new ClassPathResource("template.csv").getInputStream());
mockMvc.perform(MockMvcRequestBuilders.multipart("/csv/upload")
.file(mockMultipartFile))
.andExpect(status().isOk());
}}
When the test fails I can see this Resolved Exception: Type = org.springframework.web.multipart.support.MissingServletRequestPartException