【问题标题】:Why is MultipartFile null on POST mockMvc Test为什么 POST mockMvc 测试中的 MultipartFile 为空
【发布时间】:2022-11-11 04:32:29
【问题描述】:

当通过 MockMvc 将 MockMultiPartFile 传递到我的 POST 请求中时,当在设置步骤中正确填充文件时,它将作为 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 变量的方式而不是 @Autowiring 它,就像我在其他测试 .multipart() 函数的答案中看到的那样,但是进来的文件仍然为空,导致断言失败由于文件为空,响应不是 200。

以前的尝试:

MockMvc mockMvc 
  = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
mockMvc.perform(multipart("/perform-bpsLoad").file(file))
  .andExpect(status().isOk());

【问题讨论】:

    标签: java spring-mvc junit spring-restcontroller


    【解决方案1】:

    这里同样的问题。网上有很多例子,但帖子的正文总是空的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-02
      • 2017-10-28
      • 2020-04-19
      • 1970-01-01
      • 2014-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多