0

I want to test method of receiving a list of objects, according to list of given strings. My original method:

@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 (tagRepository):

 @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 (Class holding a list of strings I want to search by)

@Getter
@Setter
@AllArgsConstructor
public class Fil {

    public Fil() {

    }

    @NotNull
    private List<String> cpes;

}

I wrote an integration test:

@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());
}
John
  • 93
  • 2
  • 12

2 Answers2

0

The HTTP 415 means: Unsupported Media Type client error response code indicates that the server refuses to accept the request because the payload format is in an unsupported format (source).

You need to provide the information on requested content type and expected response format.

Spring defaults to content-type header to application/json. So you need to tell your server that it should use json to de-serilze Tag class on post request, or specify the required type on the post request. e.g org.springframework.http.MediaType#APPLICATION_XML_VALUE or org.springframework.http.MediaType#APPLICATION_JSON

You will have a similar issue on response.

You can find an example on how to change restTemplate conntent type here POST request via RestTemplate in JSON

I suggest reading:
http://www.baeldung.com/spring-requestmapping
http://www.baeldung.com/rest-template

Haim Raman
  • 11,508
  • 6
  • 44
  • 70
  • I googled that, but that doesn't ring any bell of how to applied that information to the test. Thanks for the source tho - I will read it. I think my mistake is that I should link my "input"-cpe with the response (tag). But have no idea how to do this :/ – John Jun 03 '18 at 19:11
  • Could you share some more details like spring versions. Subset of the project on GitHub will be the best – Haim Raman Jun 04 '18 at 03:01
0

My mistake was that I didnt implement fil to create a list of objects. I should use:

Fil fil= new Fil();
fil.setCpes(Stream.of("cpe1").collect(Collectors.toList()));
John
  • 93
  • 2
  • 12