Spring MVC Controller中如何使用JUnit返回类型的方法
问题内容:
我在Spring MVC控制器上执行junit-
@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;
}
下面是我的上述方法的junit-
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工作正常..
但是我的问题是我该如何将返回类型handleRequest
返回HashMap
带有键和值对的junit 。如何验证它是否正在返回Hello World
?是否有任何方法可以做到这一点?
问题答案:
看一下Spring参考手册中的示例,这些示例中提到了使用MockMvc测试服务器端代码。假设您正在返回JSON响应:
mockMvc.perform(get("/index"))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json"))
.andExpect(jsonPath("$.greeting").value("Hello World"));
顺便说一句-
切勿捕获并吞下@Test
方法中的异常,除非您想忽略该异常并防止其失败通过测试。如果编译器抱怨您的测试方法调用了引发异常的方法而您没有处理该异常,则只需将方法签名更改为即可throws Exception
。