There are two methods in my Controller, the POST controller:
@Post
HttpResponse<Publisher<ControllerResponseModel>> post(@Body String designJson) throws JsonProcessingException {
Publisher<ControllerResponseModel> response = designService.save(designJson);
return HttpResponse.created(response);
}
... and the Error handler if the JSON is malformed:
@Error(exception = JsonProcessingException.class)
HttpResponse<Publisher<ErrorModel>> jsonProcessingException(HttpRequest request, JsonProcessingException exception) {
return HttpResponse.badRequest(Mono.just(new ErrorModel(exception.getMessage())));
}
When I run the application, everything works as intended. A response of ErrorModel is shown for malformed JSON; a response of the proper type for properly formed JSON.
But I can't seem to unit test the error handlers in the Controller.
My hope was something like this would work. I mock out the service and have it throw the proper exception. But when it's run, the thrown exception fails the test and the response object isn't populated or asserted against.
@Test
void post_malformedJson() throws IOException {
final String jsonData = "var: 37";
final JsonParser parser = JsonFactory.builder().build().createParser(jsonData);
doThrow(new JsonParseException(parser, "")).when(designService).save(anyString());
HttpResponse<Publisher<ControllerResponseModel>> response = instance.post(jsonData);
assertThat(response.getBody().isPresent()).isTrue();
StepVerifier.create(response.getBody().get())
.expectNext(new ErrorModel("SOMETHING"))
.expectComplete()
.verify();
}
Any tips (even if it's a completely different structure than above) on how to unit test Micronaut Error handlers?