首页 > 解决方案 > Junit:状态预期 <200> 但它是 <400>

问题描述

我正在尝试为post控制器级别的请求编写测试用例。当我通过邮递员时,我得到200 0k

@RestController
@RequestMapping("/hello")
public class HelloResource {

    @Autowired
    HelloService helloService;  

    @PostMapping("/post")
    public Hello helloPost(@RequestBody Hello hello) {
        return hello;       
    }
}

class Hello {
    private String title;   
    private String value; 

    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }
    public Hello(String title, String value) {
        super();
        this.title = title;
        this.value = value;
    }

    public Hello() {
        super();
    }           
}

测试用例

@Test
public void helloPost() throws Exception {

    String json = "{\n" +
                  " \"title\":\"Greetting\", \n" + 
                  " \"value\":\"Hello world\",\n" + 
                  "}";

    mockMvc.perform(post("/hello/post")
                     .contentType(MediaType.APPLICATION_JSON)
                     .content(json))
                     .andExpect(status().isOk());

标签: springspring-bootunit-testingjunit4

解决方案


试试下面的json:-

String json = "{\"title\":\"Greetting\",\"value\":\"Hello world\"}";

推荐阅读