Spring Boot:RestTemplate的POST调用未返回创建状态代码。

huangapple go评论74阅读模式
英文:

Spring boot : RestTemplate POST call does not return created status code

问题

我是新手学习Spring Boot Rest Template。我尝试编写用于Rest Template POST调用的单元测试用例。
我已经创建了一个用户控制器来发送虚拟数据。
用户控制器编写的POST调用的方式是否正确,适合单元测试吗?如果不是,正确的编写方式是什么?我从用户控制器返回的响应是否正确?我应该返回状态代码200还是201?
有人可以帮助我吗?

以下是用户控制器:

@PostMapping("/users")
public User createUser(@RequestBody User user){
    List<String> messages = new ArrayList<>();
    messages.add("Hi");

    User createUser = new User();
    createUser.setId(1);
    createUser.setName("John");
    createUser.setAge(22);
    createUser.setMessages(messages);
    return user;
}

以下是用于POST调用的单元测试用例:

@Test
public void testSuccessPostUser() throws Exception{
    String baseUrl = "http://localhost:8080/users";
    List<String> messages = new ArrayList<>();
    messages.add("Hi");

    User user = new User();
    user.setId(1);
    user.setName("John");
    user.setAge(22);
    user.setMessages(messages);

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

    HttpEntity<User> httpEntity = new HttpEntity<>(user, httpHeaders);

    HttpHandler httpHandler = new HttpHandler();
    ResponseEntity<User>  actual = httpHandler.sendPost(baseUrl, httpHeaders, user, User.class);

    //验证请求成功
    assertEquals(HttpStatus.CREATED, actual.getStatusCode());
    assertEquals(201, actual.getStatusCodeValue());
    assertTrue(responseBody.contains(id));
}
英文:

I'm new to spring boot rest template. I'm trying write unit test case for rest template post call.
I've created a user controller to send the dummy data.
Is the Usercontroller written for POST call is correct for unit test? If not what is the correct way to write it? Is the response I'm returning from usercontroller correct? Should I return status code as 200 or 201?
Can someone help me?

Below is the usercontroller

@PostMapping(&quot;/users&quot;)
    public User createUser(@RequestBody User user){
        List&lt;String&gt; messages = new ArrayList&lt;&gt;();
        messages.add(&quot;Hi&quot;);

        User createUser = new User();
        createUser.setId(1);
        createUser.setName(&quot;John&quot;);
        createUser.setAge(22);
        createUser.setMessages(messages);
        return user;
    }

Below id the unit test case for post call:

@Test
    public void testSuccessPostUser() throws Exception{
        String baseUrl = &quot;http://localhost:8080/users&quot;;
        List&lt;String&gt; messages = new ArrayList&lt;&gt;();
        messages.add(&quot;Hi&quot;);

        User user = new User();
        user.setId(1);
        user.setName(&quot;John&quot;);
        user.setAge(22);
        user.setMessages(messages);

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

        HttpEntity&lt;User&gt; httpEntity = new HttpEntity&lt;&gt;(user, httpHeaders);

        HttpHandler httpHandler = new HttpHandler();
        ResponseEntity&lt;User&gt;  actual = httpHandler.sendPost(baseUrl, httpHeaders, user, User.class);

        //verify request succeed
        assertEquals(HttpStatus.CREATED, actual.getStatusCode());
        assertEquals(201, actual.getStatusCodeValue());
        assertTrue(responseBody.contains(id);
    }

答案1

得分: 1

POST默认返回200。

如果您希望它返回201,请添加以下内容:

@ResponseStatus(HttpStatus.CREATED)
@PostMapping("/users")
public User createUser(@RequestBody User user){
英文:

POST returns 200 by default.

If you want to make it return 201 add this:

@ResponseStatus(HttpStatus.CREATED)
@PostMapping(&quot;/users&quot;)
public User createUser(@RequestBody User user){

答案2

得分: 1

如果您想返回自定义状态代码,应该返回ResponseEntity

@PostMapping("/users")
public ResponseEntity<User> createUser(@RequestBody User user){
    ...
    return new ResponseEntity(user, HttpStatus.CREATED);
}

如果您想了解POST方法的正确HTTPS状态码,我建议阅读这个链接:https://stackoverflow.com/questions/43327963/what-status-code-should-we-return-if-the-post-succeeds-but-does-not-result-in-cr

英文:

If you want to return custom status codes, you should return RepsponseEntity:

@PostMapping(&quot;/users&quot;)
public ResposneEntity&lt;User&gt; createUser(@RequestBody User user){
    ...
    return new ResponseEntity(user, HttpStatus.CREATED);
}

If you want to know correct https statuses for a POST method I suggest to read this: https://stackoverflow.com/questions/43327963/what-status-code-should-we-return-if-the-post-succeeds-but-does-not-result-in-cr

答案3

得分: 1

首先,用于测试HTTP控制器的方法是使用MockMvc

示例测试:

mockMvc.perform(post("/users")
       .contentType(MediaType.APPLICATION_JSON)
       .content("{ \"id\": 1, \"Name\": \"John\", \"Age\": 22 }")
       .accept(MediaType.APPLICATION_JSON))
       .andExpect(status().isCreated())
       .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
       .andExpect(jsonPath("$.id").value($id))
       .andExpect(jsonPath("$.value").value("some-value"));

更多详细信息请查看文档

要返回201状态码,您需要在您的控制器中添加@ResponseStatus(HttpStatus.CREATED)

英文:

First of all, for testing HTTP controller You can use MockMvc.

Examples test:

mockMvc.perform(post(&quot;/users&quot;)
       .contentType(MediaType.APPLICATION_JSON)
       .content(&quot;{ &quot;id&quot;: 1, &quot;Name&quot;: &quot;John&quot;, &quot;Age&quot;: 22 }&quot;) 
       .accept(MediaType.APPLICATION_JSON))
       .andExpect(status().isCreated())
       .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
       .andExpect(jsonPath(&quot;$.id&quot;).value($id)) 
       .andExpect(jsonPath(&quot;$.value&quot;).value(&quot;some-value&quot;));

More details in docs

To return 201 code, You need to add @ResponseStatus(HttpStatus.CREATED) in Your controller.

huangapple
  • 本文由 发表于 2020年7月30日 19:24:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/63172137.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定