2016-03-07 14 views
7

में पोस्ट करने के लिए एक JSON ऑब्जेक्ट बनाएं, मैं उपयोगकर्ता बनाने के लिए JSON पेलोड के साथ/उपयोगकर्ता URL पर POST अनुरोध निष्पादित करने के लिए मूल परीक्षण लिखना चाहता हूं। मैं कैसे JSON करने के लिए एक नई वस्तु कन्वर्ट करने के लिए नहीं मिल रहा है, और अब तक यह बहुत है, यह स्पष्ट रूप से गलत है लेकिन उद्देश्य बताते हैं:स्प्रिंग बूट परीक्षण

@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

मदद कर सकते हैं मैं के लिए बस क्या देख रहा था: ओ) – chocksaway

संबंधित मुद्दे