如何在spring mvc控制器中使用junit返回类型的方法

我在我的Spring MVC控制器上做junit –

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

以下是我对上述方法的说法 –

 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(); } } } 

以上junit工作正常..

但我的问题是如何使用键和值对返回带有HashMaphandleRequest的返回类型。如何validation它是否返回Hello World ? 有没有办法做到这一点?

请参阅Spring参考手册中的示例,这些示例涉及使用MockMvc测试服务器端代码。 假设您要返回JSON响应:

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

顺便说一句 – 永远不要在@Test方法中捕获并吞下exception,除非你想忽略该exception并防止它失败。 如果编译器抱怨您的测试方法调用了抛出exception并且您没有处理它的方法,只需将方法签名更改为throws Exception