Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a JSON object to post in Spring Boot tests

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());
like image 628
Maciej Szlosarczyk Avatar asked Mar 07 '16 22:03

Maciej Szlosarczyk


1 Answers

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

like image 89
Valerio Vaudi Avatar answered Sep 30 '22 19:09

Valerio Vaudi