如何在春季放心测试上传文件?

时间:2019-01-15 13:30:43

标签: spring api file testing rest-assured

我正在尝试创建一个使用我的API上传mp3文件的测试。我不知道该怎么做。

我的文件testsound.mp3位于我项目的resources文件夹中。

我的API代码:

@PostMapping(value = "/tracks", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Track create(@RequestParam("file") MultipartFile file) throws IOException, InvalidDataException, UnsupportedTagException {
    return trackService.createTrack(file);
}

到目前为止我的测试代码:

@Test
public void eTestUploadTrack() throws IOException {
    File file = new ClassPathResource("testsound.mp3").getFile();

    trackId = given()
            .header("X-Authorization", token)
            .param("file", file)
            .post("/tracks")
            .then()
            .statusCode(200)
            .extract()
            .path("id").toString();
}

我的项目结构:

project structure

希望任何人都可以帮助我!

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用multipart()方法进行文件上传测试。

工作代码:

    @Test
public void eTestUploadTrack() throws IOException {
    File file = new ClassPathResource("testsound.mp3").getFile();

    trackId = given()
            .header("X-Authorization", token)
            .contentType(MediaType.MULTIPART_FORM_DATA_VALUE)
            .multiPart("file", file)
            .post("/tracks")
            .then()
            .statusCode(200)
            .extract()
            .path("id").toString();
}

要进一步阅读,请访问以下链接:

  1. Example 1
  2. RestAssured JUNITs