我正在 Spring MVC Controller 上执行 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 工作正常..
但我的问题是如何 junit 返回带有键和值对的 HashMap
的 handleRequest
的返回类型。我如何验证它是否正在返回 Hello World
?有什么方法可以做到这一点吗?
最佳答案
看看at the examples in the Spring reference manual指使用MockMvc测试服务器端代码。假设您返回 JSON 响应:
mockMvc.perform(get("/index"))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json"))
.andExpect(jsonPath("$.greeting").value("Hello World"));
顺便说一句 - 永远不要在 @Test
方法中捕获并吞下异常,除非您想忽略该异常并防止其测试失败。如果编译器提示您的测试方法调用了引发异常的方法,而您没有处理它,只需将方法签名更改为 throws Exception
。
关于java - 如何在 spring mvc Controller 中 junit 方法的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22182167/