0

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

我正在使用 springMultipartBodyBuilder来构建请求的主体。然后我想对此请求进行单元测试,所以我正在使用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()我可以检查的 into 对象。是否有用于多部分请求正文的解析器?

4

1 回答 1

1

我能够使用高兴文件上传库解决这个问题:

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");
}
于 2019-10-11T18:28:30.267 回答