【发布时间】:2022-01-06 06:39:50
【问题描述】:
当我尝试发出 mockmvc 发布请求时,我必须在内容标签中传递对象列表,问题是每次我尝试使用 此方法 传递它:
public static String asJsonString(final Object obj) {
try {
final ObjectMapper mapper = new ObjectMapper();
final String jsonContent = mapper.writeValueAsString(obj);
return jsonContent;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
我收到此错误:
{"status":"NOT_ACCEPTABLE","errors":{"timestamp":"2021-11-29T11:53:11.2020882Z","message":"Wrong message format","details":"JSON parse error: Cannot deserialize instance of `java.util.ArrayList<Compania>` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList<Compania>` out of START_OBJECT token\n at [Source: (PushbackInputStream); line: 1, column: 1]"}}
我为仅保存 1 个对象所做的测试运行良好,但每当我尝试添加列表时它就会中断,这里有我的测试代码。
@Test
void successSavePostCompaniaLista() throws Exception {
Compania c1 = new Compania("Compania1 list",
"name1",
"---",
"---",
null,
null);
Compania c2 = new Compania("Compania2 list",
"name2",
"---",
"---",
null,
null);
List<Compania> companias = List.of(c1,c2);
when(companiaRepository.save(any(Compania.class))).then(returnsFirstArg());
this.mockMvc.perform(
post("/companias/lista")
.header("authorization", "Bearer " + token)
.content(asJsonString(companias)) //<-- Here gives me errors
.contentType(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isCreated())
.andExpect(jsonPath("$.result[0].success[0]").isNotEmpty())
.andExpect(jsonPath("$.result[0].success[0].name").value(c1.getName()))
.andExpect(jsonPath("$.result[0].success[1].name").value(c2.getName()));
}
工作原理与此类似,但只使用一个对象。
http的方向,其余的都ok。
谢谢!
编辑。这是我正在尝试测试的服务
public Map<String, Object> postListCompanias(List<Compania> companias) {
for (int i = 0; i < companias.size(); i++) {
Compania companiaN = companias.get(i);
companiaN.setId(null);
companiaRepository.save(companias.get(i));
System.out.println(companias.get(i));
}
Map<String, Object> mappedResult = Collections.singletonMap(
"result",
List.of(
Collections.singletonMap(
"success",
companias
)
)
);
return mappedResult;
}
这里是控制器:
@ResponseStatus(HttpStatus.CREATED)
@PostMapping("/lista")
public Map<String, Object> createCompanias(@RequestBody List<Compania> companias) {
return companiaService.postListCompanias(companias);
}
【问题讨论】:
-
您能否为您要测试的控制器添加代码?谢谢!
-
@JoãoDias 抱歉回复晚了,我已经编辑了我的帖子
标签: java json spring-boot hibernate jackson