无法使用RestAssured触发多部分请求

时间:2018-09-06 05:34:52

标签: rest-assured

我一直在尝试使用RestAssured v2.9.0发送多部分请求,但是它总是抛出错误。

控制器:

@RequestMapping(value = "/my-url", method = RequestMethod.POST, consumes = MULTIPART_FORM_DATA_VALUE)
public void saveHrPreHireForm(
            @RequestParam("form") MultipartFile formFields,
            @RequestParam("file") MultipartFile file,
            @AuthenticationPrincipal ...

RestAssured呼叫:

given().header(HEADER_NAME, HEADER_VALUE)
        .filter(new RequestLoggingFilter())
        .multiPart(getMutliPart("{//JSON FORM FIELDS}", "form", "application/json", "blob"))
        .multiPart(getMutliPart("Test-Content-In-File", "file", "text/plain", "Test.txt"))
        .when()
        .post("my-url");

错误消息:

org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'form' is not present

RestAssured日志:

Request method: POST
Request path:   http://localhost:50789/my-url
Proxy:          <none>
Request params: <none>
Query params:   <none>
Form params:    <none>
Path params:    <none>
Multiparts:     controlName=form, mimeType=application/json, charset=<none>, fileName=blob, content=[123, 345..blah blah]
                controlName=file, mimeType=text/plain, charset=<none>, fileName=Test.txt, content==[13, 34..blah blah]
Headers:        HEADER=VALUE
                Accept=*/*
                Content-Type=multipart/form-data
Cookies:        <none>
Body:           <none>

显然,Request params为空,这就是错误的原因。

我也尝试过在MockMultipartFile内发送.parameters("form", mockMultipartFile),但是没有运气。

我在网上提到了很多内容,包括this,但问题仍然存在。任何指针都表示赞赏。

1 个答案:

答案 0 :(得分:1)

解决了这个问题。

RequestSpecBuilder builder = new RequestSpecBuilder();
builder.addParam("form", "..form fields json");
builder.addParam("file", "..file");
RequestSpecification requestSpec = builder.build();

given().header(HEADER_NAME, HEADER_VALUE)
        .filter(new RequestLoggingFilter())
        .spec(requestSpec)
        .config(RestAssured.config().encoderConfig(encoderConfig().encodeContentTypeAs("application/json;charset=UTF-8", ContentType.JSON)))
        .when()
        .post("my-url");