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?
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:
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 tothrows Exception
.