如何使用 mockMvc 检查响应正文中的 JSON

How to check JSON in response body with mockMvc(如何使用 mockMvc 检查响应正文中的 JSON)
本文介绍了如何使用 mockMvc 检查响应正文中的 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

这是我在控制器中的方法,由 @Controller

This is my method inside my controller which is annotated by @Controller

@RequestMapping(value = "/getServerAlertFilters/{serverName}/", produces = "application/json; charset=utf-8")
    @ResponseBody
    public JSONObject getServerAlertFilters(@PathVariable String serverName) {
        JSONObject json = new JSONObject();
        List<FilterVO> filteredAlerts = alertFilterService.getAlertFilters(serverName, "");
        JSONArray jsonArray = new JSONArray();
        jsonArray.addAll(filteredAlerts);
        json.put(SelfServiceConstants.DATA, jsonArray);
        return json;
    }

我期待 {"data":[{"useRegEx":"false","hosts":"v2v2v2"}]} 作为我的 json.

I am expecting {"data":[{"useRegEx":"false","hosts":"v2v2v2"}]} as my json.

这是我的 JUnit 测试:

And this is my JUnit test:

@Test
    public final void testAlertFilterView() {       
        try {           
            MvcResult result = this.mockMvc.perform(get("/getServerAlertFilters/v2v2v2/").session(session)
                    .accept("application/json"))
                    .andDo(print()).andReturn();
            String content = result.getResponse().getContentAsString();
            LOG.info(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

这是控制台输出:

MockHttpServletResponse:
              Status = 406
       Error message = null
             Headers = {}
        Content type = null
                Body = 
       Forwarded URL = null
      Redirected URL = null
             Cookies = []

甚至 result.getResponse().getContentAsString() 也是一个空字符串.

Even result.getResponse().getContentAsString() is an empty string.

有人可以建议如何在我的 JUnit 测试方法中获取我的 JSON,以便我可以完成我的测试用例.

Can someone please suggest how to get my JSON in my JUnit test method so that I can complete my test case.

推荐答案

我使用 TestNG 进行单元测试.但是在 Spring Test Framework 中,它们看起来都很相似.所以我相信你的测试如下所示

I use TestNG for my unit testing. But in Spring Test Framework they both looks similar. So I believe your test be like below

@Test
public void testAlertFilterView() throws Exception {
    this.mockMvc.perform(get("/getServerAlertFilters/v2v2v2/").
            .andExpect(status().isOk())
            .andExpect(content().json("{'data':[{'useRegEx':'false','hosts':'v2v2v2'}]}"));
    }

如果你想检查检查 json 键和值,你可以使用 jsonpath.andExpect(jsonPath("$.yourKeyValue", is("WhatYouExpect")));

If you want check check json Key and value you can use jsonpath .andExpect(jsonPath("$.yourKeyValue", is("WhatYouExpect")));

您可能会发现content().json() 无法解决请添加

You might find thatcontent().json() are not solveble please add

导入静态 org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

这篇关于如何使用 mockMvc 检查响应正文中的 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)