I want to write basic test to execute a POST request on a /users URL with JSON payload to create a user. I cannot find how to convert a new object to JSON, and so far have this much, it's obviously wrong but explains the purpose:
@Test public void createUser() throws Exception {
String userJson = new User("My new User", "[email protected]").toJson();
this.mockMvc.perform(post("/users/").contentType(userJson)).andExpect(status().isCreated());
You can use jackson object mapper and then user writeValueAsString method.
So
@Autowired
ObjectMapper objectMapper;
// or ObjectMapper objectMapper = new ObjectMapper(); this with Spring Boot is useless
@Test public void createUser() throws Exception {
User user = new User("My new User", "[email protected]");
this.mockMvc.perform(post("/users/")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(user)))
.andExpect(status().isCreated());
}
I hope this can help you
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With