Search code examples
javagroovymultipartform-dataspockmicronaut

Using @Client in Spock Test for HTTP Multipart File Upload in Micronaut


I have the following signature for my Micronaut file upload controller (in Java):

@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("application/json")
@Post
public Single<IdType> uploadFile(Publisher<CompletedFileUpload> files)

And I have the following working Spock test (in Groovy):

@MicronautTest
class UploadSpecification extends Specification implements CsvFileBuilder {

  @Inject
  @Client('/')
  HttpClient client

  @Shared
  List<String> allowedMimeTypes = List.of("text/csv", "application/vnd.ms-excel")

  @Unroll
  void "upload mailings csv with content type #mediaType"() {

    given:
    MultipartBody multipartBody = MultipartBody
        .builder()
        .addPart("files", "myfile.csv", new MediaType(mediaType), createCsvAsBytes(buildCsv()))
        .build()

    when:
    HttpResponse response = client.toBlocking()
        .exchange(POST("/v1/mailings", multipartBody).contentType(MediaType.MULTIPART_FORM_DATA_TYPE))

    then:
    response.status == HttpStatus.OK

    where:
    mediaType << allowedMimeTypes
  }
}

What I would like to change about the test is: Instead of using the standard HttpClient as injected at the top of the test, I would like to use something like this:

@Inject
UploadClient uploadClient

@Client(value = "/v1/mailings")
static interface UploadClient {

  @Post
  HttpResponse postFile(...)
}

My question is, what signature, does the postFile of the client need? Will I still be able to use MultipartBody but somehow convert it to a CompletedFileUpload? I'm really not sure how to solve this and I'm a beginner when it comes to RxJava.

Any help is appreciated.


Solution

  • Please try following:

    @Client(value ="/v1/upload")
    static interface UploadClient {
    
      @Post(uri = "/mailings", produces = MediaType.MULTIPART_FORM_DATA)
      HttpResponse postFile(@Body MultipartBody file)
    
    }
    

    Add produces and the body annotation