gpt4 book ai didi

java - 如何从字符串反序列化请求多部分正文

转载 作者:行者123 更新时间:2023-12-02 00:56:29 27 4
gpt4 key购买 nike

我有一个表示请求的 multipart/form-data 主体的字符串,我想解析它,以便编写一个带有其值断言的单元测试。

我正在使用 spring MultipartBodyBuilder 来构建请求的正文。然后我想对此请求进行单元测试,因此我使用 MockWebServer 并调用 takeRequest()

需要测试的代码:

public Mono<MyType> myMethod(String property1) {
MultipartBodyBuilder bodyBuilder = new MultipartBodyBuilder();

bodyBuilder.part("property1", property1);

return webClient
.post()
.uri("/some-path")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.body(
BodyInserters.fromMultipartData(bodyBuilder.build())
)
.retrieve()
.bodyToMono(MyType.class));
}

测试:

public void myMethod() {
mockWebServer.enqueue(new MockResponse());


Mono<MyType> response = myClient.myMethod("testString");

StepVerifier.create(response)
.expectNextCount(1)
.expectComplete()
.verify();

RecordedRequest request = mockWebServer.takeRequest();

// here I want to assert that request.getBody() has a form field named "property1" with value "testString"
}

我不确定如何将 request.getBody() 解析为我可以检查的对象。是否有用于多部分请求正文的解析器?

最佳答案

我能够使用 delight-fileupload 解决这个问题图书馆:

import delight.fileupload.FileUpload;
import org.apache.commons.fileupload.FileItem;

//...

String contentType = recordedRequest.getHeader("Content-Type");
List<FileItem> fileItems = FileUpload.parse(recordedRequest.getBody().readUtf8().getBytes(), contentType);
Map<String,String> formFieldValues = new HashMap<>();
String fileContent = "";
String fileFieldName = "";
for (FileItem item : fileItems) {
item.getName();
if (item.isFormField()) {
formFieldValues.put(item.getFieldName(), item.getString());
} else {
fileContent = item.getString("UTF-8");
fileFieldName = item.getFieldName();
}
}

因此,对于您的具体情况,我认为以下方法应该可以解决问题:

public void myMethod() {
mockWebServer.enqueue(new MockResponse());

Mono<MyType> response = myClient.myMethod("testString");

StepVerifier.create(response)
.expectNextCount(1)
.expectComplete()
.verify();

RecordedRequest request = mockWebServer.takeRequest();
String contentType = recordedRequest.getHeader("Content-Type");
List<FileItem> fileItems = FileUpload.parse(recordedRequest.getBody().readUtf8().getBytes(), contentType);
assertEquals(1, iterator.size());
FileItem item = fileItems.get(0);
assertTrue(item.isFormField());
assertEquals("property1", item.getFieldName());
assertEquals("testString", item.getString("UTF-8");
}

关于java - 如何从字符串反序列化请求多部分正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57814019/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com