I ran into the same issue a while ago and did solve it by using reflection with some help from Jackson.
First populate a map with all the fields on an Object. Then add those map entries as parameters to the MockHttpServletRequestBuilder.
In this way you can use any Object and you are passing it as request parameters. I'm sure there are other solutions out there but this one worked for us:
@Test
public void testFormEdit() throws Exception {
getMockMvc()
.perform(
addFormParameters(post(servletPath + tableRootUrl + "/" + POST_FORM_EDIT_URL).servletPath(servletPath)
.param("entityID", entityId), validEntity)).andDo(print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON)).andExpect(content().string(equalTo(entityId)));
}
private MockHttpServletRequestBuilder addFormParameters(MockHttpServletRequestBuilder builder, Object object)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
SimpleDateFormat dateFormat = new SimpleDateFormat(applicationSettings.getApplicationDateFormat());
Map<String, ?> propertyValues = getPropertyValues(object, dateFormat);
for (Entry<String, ?> entry : propertyValues.entrySet()) {
builder.param(entry.getKey(),
Util.prepareDisplayValue(entry.getValue(), applicationSettings.getApplicationDateFormat()));
}
return builder;
}
private Map<String, ?> getPropertyValues(Object object, DateFormat dateFormat) {
ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(dateFormat);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.registerModule(new JodaModule());
TypeReference<HashMap<String, ?>> typeRef = new TypeReference<HashMap<String, ?>>() {};
Map<String, ?> returnValues = mapper.convertValue(object, typeRef);
return returnValues;
}