I have a REST controller that defines an interface which takes an optional request body.
@RestController
@RequestMapping(ExampleRest.EXAMPLE_URI)
public class ExampleRest {
public static final String EXAMPLE_URI = "/examples";
@RequestMapping(value = "/search", method = POST)
public Page<ExampleDto> search(@RequestBody(required = false) Searchable searchable, Pageable pageable) {
return exampleService.findAll(searchable, pageable);
}
}
The Searchable
object contains information to create a JPASpecification
. It's pretty much a dto
. I would like to make this searchable optional. I understood that @RequestBody(required = false)
should do the trick.
I have the following test, where I want to test a request without any request body.
@Test
public void post_NoCriteria_Ok() {
RequestEntity requestEntity = new RequestEntity(HttpMethod.POST, URI.create(ExampleRest.EXAMPLE_URI + "/search"));
ResponseEntity <RestResponsePage<ExampleDto>> response = restTemplate.exchange(requestEntity, new ParameterizedTypeReference <RestResponsePage<ExampleDto>> () {});
Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
}
If I run this test, it keeps failing with this response from the RestController
:
<415 Unsupported Media Type,Page 1 of 1 containing UNKNOWN instances,{Content-Type=[application/json;charset=UTF-8], Transfer-Encoding=[chunked], Date=[Wed, 13 Sep 2017 10:10:22 GMT]}>
The Code execution does not even enter search
method implementation inside of the RestController
.
As soon I provide an empty Searchable
for the test, it runs through.
Is the implementation of @RequestBody(required = false)
buggy, or what am I doing wrong here?
You need to set
Content-Type
as"application/json"
in your request while sending from@Test
file.