创建一个JSON对象以在Spring Boot测试中发布

Mac*_*zyk 11 spring json spring-boot

我想编写基本测试来在具有JSON有效负载的/ users URL上执行POST请求以创建用户.我找不到如何将新对象转换为JSON,到目前为止有这么多,这显然是错误的,但解释了目的:

@Test public void createUser() throws Exception {
    String userJson = new User("My new User", "myemail@gmail.com").toJson();
    this.mockMvc.perform(post("/users/").contentType(userJson)).andExpect(status().isCreated());
Run Code Online (Sandbox Code Playgroud)

Val*_*udi 35

您可以使用jackson对象映射器,然后使用用户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", "myemail@gmail.com");
        this.mockMvc.perform(post("/users/")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(user)))
                .andExpect(status().isCreated());
    }
Run Code Online (Sandbox Code Playgroud)

我希望这可以帮到你