我有一个用于在发布请求中上传 csv 的工作控制器。邮递员状态为 200,测试时状态为 400。我正在努力寻找问题所在。
控制器:
@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 实用程序:
public class CsvHelper {
public static String TYPE = "text/csv";
public static boolean hasCSVFormat(MultipartFile file) {
return TYPE.equals(file.getContentType());
}
}
测试:
@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());
}}
当测试失败时,我可以看到这个 Resolved Exception: Type = org.springframework.web.multipart.support.MissingServletRequestPartException