EventController { SendEventRequest sendEventRequest(Request request) { byte[] body = request.body().orElse(null); if (body == null) { String contentType = request.header(HTTPHeaders.CONTENT_TYPE).orElse(null); if (contentType == null || contentType.startsWith(ContentType.TEXT_PLAIN.mediaType)) return null; throw new BadRequestException("body must not be null", "INVALID_HTTP_REQUEST"); } try { SendEventRequest eventRequest = reader.fromJSON(body); validator.validate(eventRequest); return eventRequest; } catch (ValidationException e) { throw new BadRequestException(e.getMessage(), e.errorCode(), e); } catch (IOException e) { throw new BadRequestException(e.getMessage(), "INVALID_HTTP_REQUEST", e); } } EventController(List<String> allowedOrigins, List<String> collectCookies); Response options(Request request); Response post(Request request);  }
@Test void sendEventRequest() { var event = new Event(); event.date = ZonedDateTime.now().withZoneSameInstant(ZoneId.of("UTC")); event.result = Result.OK; event.action = "action"; event.elapsedTime = 10L; var sendEventRequest = new SendEventRequest(); sendEventRequest.events.add(event); when(request.body()).thenReturn(Optional.of(Strings.bytes(JSON.toJSON(sendEventRequest)))); var controller = new EventController(List.of(), null); SendEventRequest parsedSendEventRequest = controller.sendEventRequest(request); assertThat(parsedSendEventRequest).usingRecursiveComparison().isEqualTo(sendEventRequest); }
@Test void sendEventRequestWithEmptyBody() { var controller = new EventController(List.of(), null); when(request.body()).thenReturn(Optional.empty()); when(request.header(HTTPHeaders.CONTENT_TYPE)).thenReturn(Optional.of(ContentType.APPLICATION_JSON.toString())); assertThatThrownBy(() -> controller.sendEventRequest(request)) .isInstanceOf(BadRequestException.class) .hasMessageContaining("body must not be null"); when(request.header(HTTPHeaders.CONTENT_TYPE)).thenReturn(Optional.of(ContentType.TEXT_PLAIN.toString())); assertThat(controller.sendEventRequest(request)).isNull(); }