如何从字符串反序列化请求多部分主体

时间:2019-09-05 23:25:16

标签: java unit-testing mockwebserver spring-webclient

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

我正在使用弹簧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()解析为可以检查的对象。是否有用于多部分请求正文的解析器?

1 个答案:

答案 0 :(得分:0)

我能够使用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");
}