使用 TestRestTemplate 进行 Multipart POST 请求的集成测试返回 400

问题描述 投票:0回答:3

我知道类似的问题已经出现过几次,但遵循建议的修复方案并没有解决我的问题。

我有一个带有以下端点的简单控制器:

@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<String> singleFileUpload(@RequestParam("file") MultipartFile file) {
    log.debug("Upload controller - POST: {}", file.getOriginalFilename());

    // do something
}

我正在尝试使用 Spring

TestRestTemplate
为其编写集成测试,但我所有的尝试都以
400 - Bad Request
结束(没有日志说明控制台中出了什么问题)。

控制器内的日志没有被命中,因此在到达那里之前就失败了。

您能看一下我的测试并建议我做错了什么吗?

@Test
public void testUpload() {
    // simulate multipartfile upload
    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource("image.jpg").getFile());

    MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<String, Object>();
    parameters.add("file", file);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);

    HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<MultiValueMap<String, Object>>(parameters, headers);

    ResponseEntity<String> response = testRestTemplate.exchange(UPLOAD, HttpMethod.POST, entity, String.class, "");

    // Expect Ok
    assertThat(response.getStatusCode(), is(HttpStatus.OK));
}
java spring spring-boot junit resttemplate
3个回答
31
投票

我尝试了以下方法:

@Test
public void testUpload() {
    LinkedMultiValueMap<String, Object> parameters = new LinkedMultiValueMap<String, Object>();
    parameters.add("file", new org.springframework.core.io.ClassPathResource("image.jpg"));

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);

    HttpEntity<LinkedMultiValueMap<String, Object>> entity = new HttpEntity<LinkedMultiValueMap<String, Object>>(parameters, headers);

    ResponseEntity<String> response = testRestTemplate.exchange(UPLOAD, HttpMethod.POST, entity, String.class, "");

    // Expect Ok
    assertThat(response.getStatusCode(), is(HttpStatus.OK));
}

如您所见,我使用

org.springframework.core.io.ClassPathResource
作为文件的对象,并且 ti 的工作就像一个魅力

希望有用

安吉洛


3
投票
如果您想使用

FileSystemResource

,也可以使用 
java.nio.file.Path

包装:

org.springframework.core.io.FileSystemResource

例如,您可以这样做:

new FileSystemResource(Path.of("src", "test", "resources", "image.jpg"))

完整代码示例:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UploadFilesTest {

    private final TestRestTemplate template;

    @Autowired
    public UploadFilesTest(TestRestTemplate template) {
        this.template = template;
    }

    @Test
    public void uploadFileTest() {
        var multipart = new LinkedMultiValueMap<>();
        multipart.add("file", file());

        final ResponseEntity<String> post = template.postForEntity("/upload", new HttpEntity<>(multipart, headers()), String.class);

        assertEquals(HttpStatus.OK, post.getStatusCode());
    }

    private HttpHeaders headers() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        return headers;
    }

    private FileSystemResource file() {
        return new FileSystemResource(Path.of("src", "test", "resources", "image.jpg"));
    }
}

休息控制器:

@RestController
public class UploadEndpoint {
    @PostMapping("/upload")
    public void uploadFile(@RequestParam("file") MultipartFile file) {
        System.out.println(file.getSize());
    }
}

0
投票

由于

MockMultipartFile
继承自
MultipartFile
,我们可以访问
getResource()
方法。我的实现如下:

我构造了一个数组

MockMultipartFiles

@NotNull
    private static MockMultipartFile[] mockMultipartFiles() {
        Path path = Paths.get("src/test/resources/uploads/");

        assertTrue(Files.exists(path));

        File dir = new File(path.toUri());
        assertNotNull(dir);

        File[] files = dir.listFiles();
        assertNotNull(files);

        return Arrays.stream(files).map(file -> {
                    try {
                        return new MockMultipartFile(
                                file.getName(),
                                file.getName(),
                                Files.probeContentType(file.toPath()),
                                Files.readAllBytes(file.toPath())
                        );
                    } catch (IOException ignored) {
                        throw new CustomServerError("unable to convert files in %s to a file".formatted(path.toString()));
                    }
                })
                .toArray(MockMultipartFile[]::new);
    }

将 MockMultipartFiles 添加到

LinkedMultiValueMap
中,作为
Resource

@NotNull
    public static MultiValueMap<String, Object> mockMultiPart(String dto) {
        MultiValueMap<String, Object> multipart = new LinkedMultiValueMap<>();

        // add image files to request
        for (var resource : mockMultipartFiles()) {
            multipart.add("files", resource.getResource());
        }

        // create dto
        HttpHeaders metadataHeaders = new HttpHeaders();
        metadataHeaders.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        multipart.add("dto", new HttpEntity<>(dto, metadataHeaders));

        return multipart;
    }
© www.soinside.com 2019 - 2024. All rights reserved.