集成测试spring restTemplate(POST-->通过列表和接收列表)
我想测试根据给定字符串列表接收对象列表的方法。 我最初的方法是:集成测试spring restTemplate(POST-->通过列表和接收列表),spring,testing,resttemplate,Spring,Testing,Resttemplate,我想测试根据给定字符串列表接收对象列表的方法。 我最初的方法是: @RequestMapping(value = "/fil/", method = RequestMethod.POST) @ResponseStatus(value = HttpStatus.OK) public ResponseEntity<List<Tag>> findAllByCpe(@RequestBody Fil fil) { return ResponseEntity.ok(tagR
@RequestMapping(value = "/fil/", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public ResponseEntity<List<Tag>> findAllByCpe(@RequestBody Fil fil) {
return ResponseEntity.ok(tagRepository.findAllBy(fil));
}
查询标记库:
@Query("SELECT t FROM Tag t WHERE (t.cpe IS NULL OR t.cpe IN (:#{#fil.cpes}))")
List<Tag> findAllBy(@Param("fil") Fil fil);
Fil类,包含我要搜索的字符串列表
@Getter
@Setter
@AllArgsConstructor
public class Fil {
public Fil() {
}
@NotNull
private List<String> cpes;
}
我写了一个集成测试:
@Test
public void FindTagGivenListOfCpes() {
//GIVEN
List<String> cpes = new ArrayList<>();
cpes .add("C1");
cpes .add("C2");
cpes .add("C3");
List<Tag> tagList = (List<Tag>) tagTestBuilder
.saved()
.itemList()
.build();
//WHEN
ResponseEntity<Tag[]> response = restTemplate.postForEntity(TagsResourceConstants.PATH + "/fil/", cpes, Tag[].class);
//THEN
assertEquals(HttpStatus.OK.value(), response.getStatusCodeValue());
}
HTTP 415表示:不支持的媒体类型客户端错误响应代码表示服务器拒绝接受请求,因为有效负载格式为不支持的格式 您需要提供有关请求的内容类型和预期响应格式的信息 Spring默认为application/json的content-type头。 因此,您需要告诉您的服务器,它应该在post请求中使用json来解除标记类的序列化,或者在post请求中指定所需的类型。 例如 org.springframework.http.MediaTypeAPPLICATION_XML_值或org.springframework.http.MediaTypeAPPLICATION_JSON 您在回复时也会遇到类似的问题 您可以在这里找到如何更改restTemplate连接类型的示例 我建议阅读:
我的错误是我没有实现fil来创建对象列表。 我应该使用:
Fil fil= new Fil();
fil.setCpes(Stream.of("cpe1").collect(Collectors.toList()));
我用谷歌搜索了一下,但这并没有告诉你如何将这些信息应用到测试中。谢谢你的消息来源,我会读的。我认为我的错误是我应该将我的输入cpe与响应标签链接起来。但是我不知道如何做到这一点:/你能分享一些更多的细节,比如spring版本吗。GitHub上的项目子集将是最好的