2016-03-07 22 views
7

我想要編寫基本測試以在具有JSON有效內容的/ users URL上執行POST請求來創建用戶。我怎麼也找不到一個新的對象轉換爲JSON,到目前爲止,有這麼多,這顯然是錯誤的,但解釋的目的:創建一個JSON對象,以便在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()); 

回答

14

您可以使用傑克遜對象映射,然後用戶writeValueAsString方法。

所以

@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()); 
    } 

我希望這可以幫助你

+0

正是我一直在尋找:O) – chocksaway

相關問題