How to junit return type of a method in spring mvc

2019-06-07 05:33发布

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条回答
男人必须洒脱
2楼-- · 2019-06-07 06:23

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.

查看更多
登录 后发表回答