MockMvc POST测试中MultipartFile为何为null?
Spring Boot MockMvc POST请求中MultipartFile始终为null的问题
问题描述
Spring Boot项目里用MockMvc发起POST请求,setup步骤已经正确初始化了MockMultipartFile,但控制器接收的MultipartFile始终是null。
控制器代码
@PostMapping(path = MANUAL_TRIGGER) private @ResponseBody ResponseEntity<String> bpsDataLoad( @RequestParam(required = false) MultipartFile positionFile) throws IOException {
测试代码
@RunWith(SpringRunner.class) @SpringBootTest @ActiveProfiles(profiles = {"test"}) @AutoConfigureMockMvc(addFilters = false) class BPSDataLoadControllerTest { @Autowired private JdbcTemplate jdbcTemplate; @Autowired MockMvc mockMvc; @Value("${spring.jpa.properties.hibernate.default_schema}") String defaultSchema; MockMultipartFile file; MockMultipartFile invalidFile; Path path = Paths.get("src/test/resources/testdata/oneposition.txt"); Path invalidPath = Paths.get("src/test/resources/testdata/invalidposition.txt"); String name = "file.txt"; String originalFileName = "file.txt"; String contentType = "text/plain"; byte[] content = null; byte[] invalidContent = null; @BeforeEach public void setup() { try { content = Files.readAllBytes(path); invalidContent = Files.readAllBytes(invalidPath); } catch (final IOException e) { } file = new MockMultipartFile(name, originalFileName, contentType, content); invalidFile = new MockMultipartFile(name, originalFileName, contentType, invalidContent); JdbcTestUtils.deleteFromTables(jdbcTemplate, defaultSchema + ".bps_position_table"); } @Test @Disabled("File is coming in as null, works on smoke test.") public void bpsDataLoadTestOK() throws Exception { mockMvc .perform(MockMvcRequestBuilders.multipart("/perform-bpsLoad").file(file)) .andExpect(status().isOk()) .andExpect(content().contentType("text/plain;charset=UTF-8")); } }
已尝试操作
试过用@WebApplicationContext初始化MockMvc,问题依旧,控制器接收的文件还是null,断言失败。尝试代码:
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); mockMvc.perform(multipart("/perform-bpsLoad").file(file)) .andExpect(status().isOk());
修复方案
- 匹配参数名称:控制器
@RequestParam的参数名是positionFile,但测试里创建MockMultipartFile时第一个参数用的是file.txt,两者不匹配导致映射失败。修改测试代码中MockMultipartFile的第一个参数为positionFile:file = new MockMultipartFile("positionFile", originalFileName, contentType, content); invalidFile = new MockMultipartFile("positionFile", originalFileName, contentType, invalidContent); - 修正控制器方法权限:当前控制器方法是
private,Spring无法正确处理请求,改成public:@PostMapping(path = MANUAL_TRIGGER) public @ResponseBody ResponseEntity<String> bpsDataLoad( @RequestParam(required = false) MultipartFile positionFile) throws IOException { - 校验请求路径:确认测试中使用的
/perform-bpsLoad和控制器MANUAL_TRIGGER常量定义的路径完全一致,避免拼写错误。
内容的提问来源于stack exchange,提问作者Beez
相关产品推荐
相关产品推荐

