如何在spring mvc控制器中使用junit返回类型的方法 [英] How to junit return type of a method in spring mvc controller

查看:177
本文介绍了如何在spring mvc控制器中使用junit返回类型的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am doing junit on my Spring MVC controller -

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

And below is my junit for the above method -

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工作正常..

Above junit works fine..

但我的问题是如何将 handleRequest 的返回类型设为junit,返回 HashMap 带键和值对..如何验证它是否返回 Hello World ?是否有任何方法可以做到这一点?

But my question is how do I junit the return type of handleRequest which is returning a HashMap with key and value pair.. How do I verify that it is returning Hello World? Is there any method to do that as well?

推荐答案

看看参考Spring参考手册中的示例使用MockMvc测试服务器端代码。假设您正在返回JSON响应:

Take a look at the examples in the Spring reference manual referring to using MockMvc to test server-side code. Assuming you are returning a JSON response:

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

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

By the way - never catch and swallow an exception in a @Test method, unless you want to ignore that exception and prevent it from failing the test. If the compiler is complaining that your test method called a method that throws an exception and you didn't handle it, simply change your method signature to throws Exception.

这篇关于如何在spring mvc控制器中使用junit返回类型的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆