I'm tryin to unit test a post rest service, this service takes an object (not a json) as content. The result is that I can't test it, the MockMvc object expects some json content.
Part of the controller, where Dsd is an internal class of the application :
@PostMapping(path="dsd")
@ApiOperation(value = "Sends Dsd data",response = Dsd.class)
public Dsd requestPostDsd (
@ApiParam("DSD data")
@Valid @RequestBody Dsd dsd,
HttpServletResponse response
) throws IOException, ParseException {
if (dsd.getId() != null) {
// do something
} else {
response.sendError(HttpStatus.BAD_REQUEST.value(), "the id doesn't exist");
}
return dsd;
}
In the unit testing code, I create a MockMvc object but the perform().content method expects a string json content, I can't pass my Dsd object instead.
How can test this POST api ?
Edit : part of the test code :
@Test
public void postDsdTest() throws Exception {
Dsd dsd = new Dsd();
this.mvc.perform(post("/services/latest/validation/dsd")
.header("Origin", HTTP_HEADER_ORIGIN)
.header("Accept", "application/json")
.content(dsd)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(header().string("Access-Control-Allow-Origin", HTTP_HEADER_ORIGIN))
.andExpect(status().isOk())
.andDo(MockMvcResultHandlers.print());
}
You could try to write a TestUtil class that serializes your object into a JSON string: https://www.petrikainulainen.net/programming/spring-framework/unit-testing-of-spring-mvc-controllers-rest-api/
With Jackson you can serialize objects to JSON:
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper.writeValueAsBytes(object);
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.