简体   繁体   English

spring mvc Junit使用mockito进行post方法

[英]spring mvc Junit using mockito for post method

I'm using the below junit test case for spring mvc. 我正在使用spring jun mvc的junit测试用例。 But every time I'm getting a error saying 但每次我收到错误说

java.lang.AssertionError: Content type not set java.lang.AssertionError:未设置内容类型

@Test
public void testAddNewPermission() throws Exception {

    String response = "{" + "\"response\":{"
            + "\"message\": \"Addded new permission\","
            + "\"status\": \"success\"}" + "}";

    when(userManagementHelper.addNewPermission("user", "NodeManagemnt"))
            .thenReturn(
                    new ResponseEntity<String>(response, new HttpHeaders(),
                            HttpStatus.OK));
    mockMvc.perform(
            post("/usermgmt/addNewPermission").param("username", "user")
                    .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(
                    content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.response.['status']", is("success")));
}   

Please help to resolve. 请帮忙解决。

Adding controller code. 添加控制器代码。

 @RequestMapping(value = "/addNewPermission", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody
    ResponseEntity<String> addNewPermission(
            @RequestParam("username") String userName, String permissionName) {
        return userManagementHepler.addNewPermission(userName, permissionName);
    }

There are a few things wrong with the way the controller code is written here, fixing these should get your code to work: 这里编写控制器代码的方式有一些问题,修复这些代码应该可以使代码工作:

.1. 0.1。 You are returning ResponseEntity explicitly here, which means that you don't have to annotate your response with @ResponseBody . 您在此处显式返回ResponseEntity ,这意味着您不必使用@ResponseBody注释您的响应。 ResponseEntity already encapsulate this behavior. ResponseEntity已经封装了这种行为。

.2. 0.2。 Your method is not taking in a JSON, it is simply accepting a Form post, yet you are saying that the Content-Type is json, which it is not. 你的方法不是接受JSON,它只是接受一个Form帖子,但你说的是Content-Type是json,它不是。 Since you are expecting a response of json, you should be setting the Accept header to json instead and remove the Content-Type altogether. 由于您期望json的响应,因此您应该将Accept标头设置为json,并完全删除Content-Type

I think changing these should fix your test. 我认为改变这些应该可以解决你的考试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM