【问题标题】:Create a JSON object to post in Spring Boot tests创建一个 JSON 对象以在 Spring Boot 测试中发布
【发布时间】:2016-06-21 16:19:29
【问题描述】:

我想编写基本测试以在 /users URL 上执行 POST 请求,并使用 JSON 有效负载来创建用户。我找不到如何将新对象转换为 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());

【问题讨论】:

    标签: json spring spring-boot


    【解决方案1】:

    您可以使用 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());
        }
    

    希望对你有帮助

    【讨论】:

    • 正是我想要的:O)
    • 你能用你的见解看看我的帖子吗? stackoverflow.com/questions/63312481/…
    • @IHaveAQuestion 我很困惑你的问题你解决了吗?我在对你的问题的评论中问了什么对我来说不是很清楚
    猜你喜欢
    • 2021-07-16
    • 1970-01-01
    • 2019-03-01
    • 2020-06-25
    • 2019-10-09
    • 2020-02-17
    • 2021-07-28
    • 2018-06-15
    • 2019-06-02
    相关资源
    最近更新 更多