java.lang.AssertionError: Content type not set while junit Spring MVC Controller?

给你一囗甜甜゛ 提交于 2019-11-29 07:12:47

I see a couple of issues with the request mapped method:

Ideally, you should have a @ResponseBody annotation on your method, to indicate that the returned content is to be streamed out:

@RequestMapping(value = "index", method = RequestMethod.GET)
@ResponseBody
public HashMap<String, String> handleRequest() {
    HashMap<String, String> model = new HashMap<String, String>();
    String name = "Hello World";
    model.put("greeting", name);

    return model;
}

Now with this done, your test can look like this:

mockMvc.perform(get("/index").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().contentTypeCompatibleWith("application/json"))
        .andExpect(jsonPath("$.greeting").value("Hello World"));

In your case, what is happening is Spring is trying to figure out the view name and is getting the view name as index, which is again the controller path, thus the circular view path error that you are seeing.

You should also check your request mappings:

Does get("/...") match @RequestMapping ?

If the handleRequest is never called, you will get the same error Content type not set.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!