简体   繁体   中英

Testing Spring RestTemplate for making multipart request on Android

I been digging around for a while but I did not find a proper way to unit test a multipart request from Android using Spring RestTemplate. Any suggestion? I need to mock the server in order to expect an image and a json. I will then test my requests without one of those parameters, etc.. What is the easiest way for doing so? So far I been trying using the MockRestServiceServer class for moking the server but cannot find a way to make it expect parameters. Hope on your kindness. Here is the request I would like to test:

MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<String,Object>();

        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.MULTIPART_FORM_DATA);
        header.add("Authorization",value);

        // creating an HttpEntity for the JSON part
        HttpHeaders jsonHeader = new HttpHeaders();
        jsonHeader.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> jsonHttpEntity = new HttpEntity<>(json_data, jsonHeader);

        // creating an HttpEntity for the binary part
        HttpHeaders pictureHeader = new HttpHeaders();
        pictureHeader.setContentType(MediaType.IMAGE_JPEG);
        HttpEntity<FileSystemResource> picturePart = new HttpEntity<>(new FileSystemResource(message_data.photo_uri), pictureHeader);

        multipartRequest.add("picPart",picturePart);
        multipartRequest.add("jsonPart",jsonHttpEntity);

        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(multipartRequest, header);

        String result = restTemplate.postForObject(message_data.server_url, requestEntity, String.class);

For mocking Rest controller class, you can use either:
1) MockMvc: https://docs.spring.io/spring-security/site/docs/current/reference/html/test-mockmvc.html
2) Restassured : http://rest-assured.io/ 3) WireMock

For mocking whole server:
1) WireMock: http://wiremock.org/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM