【问题标题】:How to check returntype in Spring Unittest using MockMVC?如何使用 MockMVC 检查 Spring Unit Test 中的返回类型?
【发布时间】:2016-03-05 13:30:57
【问题描述】:

我要测试的Spring方法

@RequestMapping(value="/files", method=RequestMethod.GET)
@ResponseBody
public List<FileListRequest> get() {
   return getMainController().getAllFiles();
}

我想确保所有对 /files 的调用都会以 List[FileListRequest] 响应。怎么样?
这是测试应该采用的方法。

@Test
public void testGetAll() throws Exception {
    this.mockMvc.perform(get("/files").accept("application/json"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(SOMETHING);
}

我可以简单地替换 SOMETHING 还是我完全错了?

我可以对 perform() 返回的对象运行断言方法吗?

【问题讨论】:

  • 您可以使用json path 来测试响应是否包含特定数据

标签: spring unit-testing mockmvc


【解决方案1】:

编辑:

MvcResult result =   this.mockMvc.perform(get("/files").accept("application/json"))
            .andExpect(status().isOk())
             .andReturn();

String content = result.getResponse().getContentAsString();

// 使用 Gson 或 Jackson 将 json String 转换为 Respective 对象

ObjectMapper mapper = new ObjectMapper();
TypeFactory typeFactory=objectMapper.getTypeFactory();
List<SomeClass> someClassList =mapper.readValue(content , typeFactory.constructCollectionType(List.class, SomeClass.class));

//在此处声明您的列表


您可以使用Json Path 检查您的回复中是否存在特定数据

旧项目的代码截图

mockMvc.perform(get("/rest/blogs")) .contentType(MediaType.APPLICATION_JSON))
                .andExpect(jsonPath("$.blogs[*].title",
                        hasItems(endsWith("Title A"), endsWith("Title B"))))
                .andExpect(status().isOk());

【讨论】:

  • 有没有办法直接使用预期的返回对象,在这种情况下是列表?
  • @John Yes.. 我会用编辑更新答案,但不建议像这样测试休息响应。
  • 好的。我只需要检查一件事:返回类型是预期的返回类型(是否返回列表,...)。返回的对象的确切内容是什么现在并不重要。
  • @John 检查我的编辑。没试过,但希望能成功
  • 好的!使用 MockMVC 进行简单类型检查如此复杂的原因是什么?
【解决方案2】:
  1. 您不能使用contentType 来检查实例的类别。 Content-Type 用于确定在 HTTP(S) 请求/响应中发送/返回的文本格式,与编程类型检查无关。它只规定请求/响应在json/text-plain/xml等。

  2. 1234563 @ 检查列表中第一项的类别,jsonPath

一个工作的 sn-p:

import static org.hamcrest.Matchers.instanceOf;

...

@Test
public void testBinInfoControllerInsertBIN() throws Exception {
    when(this.repository.save(mockBinInfo)).thenReturn(mockBinInfo);

    this.mockMvc.perform(post("/insert")
            .content("{\"id\":\"42\", \"bin\":\"touhou\", \"json_full\":\"{is_json:true}\", \"createAt\":\"18/08/2018\"}")
            .accept(MediaType.APPLICATION_JSON_UTF8_VALUE)
            .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
            )
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(status().isCreated())
        .andExpect(jsonPath("$[0]", instanceOf(BinInfo.class)))
        .andExpect(jsonPath("$[0].bin", is("touhou")));


}

如果您想检查列表中的每个项目......也许它是多余的?我还没有看到代码检查列表中的每一项,因为您必须进行迭代。当然有办法。

【讨论】:

    猜你喜欢
    • 2016-08-02
    • 2015-11-23
    • 2013-08-03
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    • 1970-01-01
    • 2021-04-01
    相关资源
    最近更新 更多