0

I have a string representing a multipart/form-data body of a request and I want to parse it in order to write a unit test with assertions for its values.

I'm using spring MultipartBodyBuilder for building the body of the request. Then I want to have unit test for this request, so I'm using MockWebServer and calling takeRequest()

The code needs to be tested:

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));
}

The test:

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"
}

I'm not sure how to parse the request.getBody() into object that I can examine. Is there a parser for multipart request body?

Yaniv
  • 144
  • 1
  • 11

1 Answers1

1

I was able to solve this using the delight-fileupload library:

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();
    }
}

So, for your specific case, I think the following should do the trick:

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");
}
akokskis
  • 1,486
  • 15
  • 32