Question

I'm using the below junit test case for spring mvc. But every time I'm getting a error saying

java.lang.AssertionError: Content type not set

@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);
    }
Was it helpful?

Solution

There are a few things wrong with the way the controller code is written here, fixing these should get your code to work:

.1. You are returning ResponseEntity explicitly here, which means that you don't have to annotate your response with @ResponseBody. ResponseEntity already encapsulate this behavior.

.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. Since you are expecting a response of json, you should be setting the Accept header to json instead and remove the Content-Type altogether.

I think changing these should fix your test.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top