java - 如何在 spring mvc Controller 中 junit 方法的返回类型

标签 java spring spring-mvc junit spring-mvc-test

我正在 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 返回带有键和值对的 HashMaphandleRequest 的返回类型。我如何验证它是否正在返回 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/

相关文章:

Java Json/Gson 将 json 编码的字符串放入 jsonObject 中,不进行字符串转义

hibernate - 如何在 Hibernate 中为 Multi-Tenancy 配置多个数据源

java - 强制浏览器缓存 Spring MVC 的 JS 响应

java - Spring @Transactional 注释使我的类无法 Autowiring

java - 如何在 Java EE 中运行并行进程

java - xmemcached 设置错误 ArrayIndexOutOfBounds

java - Spring构造函数注入(inject)和 super 调用冗长

java - Jetty、Jersey 和 Spring 的 NoInitialContextException

java - 这个创建新对象的 REST 方法到底是如何工作的?

系统重启后MySql数据库恢复到之前的状态