Last active
April 16, 2021 08:11
-
-
Save nikolavojicic/5f8002e5f19cdb20b2979dcfc54df494 to your computer and use it in GitHub Desktop.
RestAssured + multipart/form-data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Nota bene: Add @JsonIgnore to MultiPart fields | |
public static final ObjectMapper MAPPER = new ObjectMapper() | |
.configure(FAIL_ON_UNKNOWN_PROPERTIES, false) | |
.configure(FAIL_ON_EMPTY_BEANS, false); | |
public static final TypeReference<Map<String, Object>> | |
MAP_TYPE_REF = new TypeReference<>() {}; | |
public static Map<String, Object> toMap(Object obj) { | |
return MAPPER.convertValue(obj, MAP_TYPE_REF); | |
} | |
public static final Converter<String, String> TO_SNAKE_CASE | |
= LOWER_CAMEL.converterTo(LOWER_UNDERSCORE); | |
@SneakyThrows | |
public static RequestSpecification givenMultiPartRequest(Object obj) { | |
var spec = given().formParams(toMap(obj)); | |
for (var method : obj.getClass().getDeclaredMethods()) { | |
var ctrl = method.getName(); | |
if (!ctrl.startsWith("get")) | |
continue; | |
ctrl = ctrl.replace("get", ""); | |
ctrl = toLowerCase(ctrl.charAt(0)) + ctrl.substring(1); | |
var type = method.getReturnType(); | |
if (MultipartFile.class.isAssignableFrom(type)) { | |
var mp = (MultipartFile) method.invoke(obj); | |
if (mp != null) | |
spec.multiPart(TO_SNAKE_CASE.convert(ctrl), mp.getName(), mp.getBytes()); | |
} else if (Collection.class.isAssignableFrom(type)) { | |
var coll = (Collection<?>) method.invoke(obj); | |
if (coll != null && !coll.isEmpty() && MultipartFile.class | |
.isAssignableFrom(coll.toArray()[0].getClass())) | |
for (var elt : coll) { | |
var mp = (MultipartFile) elt; | |
spec.multiPart(TO_SNAKE_CASE.convert(ctrl), mp.getName(), mp.getBytes()); | |
} | |
} | |
} | |
return spec; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment