1

我想测试的 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);
}

我可以简单地替换一些东西还是我完全错了?

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

4

2 回答 2

3

编辑:

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());
于 2016-03-05T13:41:25.567 回答
1
  1. 您不能用于contentType检查实例的类别。这Content-Type是确定在 HTTP(S) 请求/响应中发送/返回的文本格式,与编程类型检查无关。它只规定请求/响应在json/ text-plain/xml等。

  2. 为了检查响应中返回的对象的类型,我们假设响应是 JSON 格式(Spring boot 中内置的 Jackson 将执行(un)编组),我们只是org.hamcrest.Matchers.instanceOf(Class<?> type)用来检查第一项的类列表,带有jsonPath.

一个工作片段:

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")));


}

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

于 2018-07-16T10:39:36.420 回答