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

后端 未结 2 438
一向
一向 2020-12-18 02:07

I am using JUnit to test my Spring MVC controller. Below is my method which returns a index.jsp page and shows Hello World on the screen -

相关标签:
2条回答
  • 2020-12-18 02:26

    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.

    0 讨论(0)
  • 2020-12-18 02:33

    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.

    0 讨论(0)
提交回复
热议问题