【问题标题】:How to junit return type of a method in spring mvc controller如何在spring mvc控制器中junit返回方法的类型
【发布时间】:2014-04-06 14:11:00
【问题描述】:

我在我的 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。我如何验证它是否返回Hello World?有什么方法也可以做到吗?

【问题讨论】:

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


    【解决方案1】:

    看看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

    【讨论】:

    • 谢谢.. 那行得通.. 还有一件事假设我的handleRequest 方法接受一个字符串参数,那么我将如何从我的junit 测试中传递它?
    • 链接文档中包含的@AKIWEB,请查看“执行请求”部分
    猜你喜欢
    • 1970-01-01
    • 2015-06-04
    • 1970-01-01
    • 2012-10-02
    • 2018-07-21
    • 2014-12-14
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    相关资源
    最近更新 更多