2016-03-07 9 views
7

Voglio scrivere test di base per eseguire una richiesta POST su un URL/utenti con payload JSON per creare un utente. Non riesco a trovare come convertire un nuovo oggetto JSON, e finora hanno così tanto, è ovviamente sbagliato, ma spiega lo scopo:Creare un oggetto JSON per postare nei test Spring Boot

@Test public void createUser() throws Exception { 
    String userJson = new User("My new User", "[email protected]").toJson(); 
    this.mockMvc.perform(post("https://stackoverflow.com/users/").contentType(userJson)).andExpect(status().isCreated()); 

risposta

14

È possibile utilizzare Jackson mapper oggetto e quindi il metodo utente writeValueAsString.

Così

@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("https://stackoverflow.com/users/") 
       .contentType(MediaType.APPLICATION_JSON) 
       .content(objectMapper.writeValueAsString(user))) 
       .andExpect(status().isCreated()); 
    } 

Spero che questo può aiutare a

+0

Proprio quello che cercavo: O) – chocksaway

Problemi correlati