如何使用 RestAssured 发送多部分请求?

How to send a multipart request with RestAssured?

我有 @Controller 方法签名如下:

@PostMapping
@ResponseBody
public ResponseEntity<Result> uploadFileAndReturnJson(@RequestParam("file") MultipartFile file) {}

我想在不实际创建任何文件的情况下构造多部分请求。我试过这样做:

private MultiPartSpecification getMultiPart() {
    return new MultiPartSpecBuilder("111,222")
            .mimeType(MimeTypeUtils.MULTIPART_FORM_DATA.toString())
            .controlName("file")
            .fileName("file")
            .build();
}

Response response = RestAssured.given(this.spec)
            .auth().basic("admin", "admin")
            .multiPart(getMultiPart())
            .when().post(URL);

很遗憾,我收到了回复:

Required request part 'file' is not present

我尝试查看 RestAssured 单元测试,看来我做得对。如果我尝试传递 byte[] 或 InputStream 而不是 String,则会抛出异常:

Cannot retry request with a non-repeatable request entity.

感谢您的帮助。

您的代码看起来不错,应该可以与 byte[] 一起使用。您可以像下面那样使用 MultiPartSpecBuilder(byte[] content)

private MultiPartSpecification getMultiPart() {
         return new MultiPartSpecBuilder("Test-Content-In-File".getBytes()).
                fileName("book.txt").
                controlName("file").
                mimeType("text/plain").
                build();
   }

有关 byte[] 错误的详细信息可在 https://github.com/rest-assured/rest-assured/issues/507 中找到。根据这个你应该尝试像下面这样的抢占式基本身份验证。

.auth().preemptive.basic("admin", "admin")
try {

    RestAssured.given()
            .header(new Header("content-type", "multipart/form-data"))
            .multiPart("file",new File( "./src/main/resources/test.txt"))
            .formParam("description", "This is my doc")
            .auth().preemptive().basic(loginModel.getUsername(), loginModel.getPassword())
            .when()
            .post(URL)
            .then()
            .assertThat()
            .body(matchesJsonSchemaInClasspath("schemas/members/member-document.json"));
}
catch(Exception e) {
    Assert.assertEquals(false, true);
    logger.error(e.getMessage(), e);
}