2016-03-07 11 views
7

JSONペイロードを持つ/ users URLでPOSTリクエストを実行してユーザーを作成するための基本テストを作成したいと思います。JSONオブジェクトを作成してSpringブートテストで投稿する

@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方法を使用することができます。私は、それは明らかに間違っているのですが、目的を説明し、JSONに新しいオブジェクトを変換する方法を見つけて、これまであまりを持つことはできません。

ので

@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

関連する問題