How to junit return type of a method in spring mvc controller

☆樱花仙子☆ 提交于 2020-01-03 04:07:26

问题


I am doing junit on my Spring MVC controller -

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

    return model;
}

And below is my junit for the above method -

public class ControllerTest {

    private MockMvc mockMvc;

    @Before
    public void setup() throws Exception {
    this.mockMvc = standaloneSetup(new Controller()).build();
    }

    @Test
    public void test01_Index() {

    try {
        mockMvc.perform(get("/index")).andExpect(status().isOk());

    } catch (Exception e) {
        e.printStackTrace();
    }
    }
}

Above junit works fine..

But my question is how do I junit the return type of handleRequest which is returning a HashMap with key and value pair.. How do I verify that it is returning Hello World? Is there any method to do that as well?


回答1:


Take a look at the examples in the Spring reference manual referring to using MockMvc to test server-side code. Assuming you are returning a JSON response:

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

By the way - never catch and swallow an exception in a @Test method, unless you want to ignore that exception and prevent it from failing the test. If the compiler is complaining that your test method called a method that throws an exception and you didn't handle it, simply change your method signature to throws Exception.



来源:https://stackoverflow.com/questions/22182167/how-to-junit-return-type-of-a-method-in-spring-mvc-controller

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