### Question:
ExceptionAuditor { public boolean auditException(ApplicationException exception, Optional<SessionId> sessionId) { boolean isAudited = exception.isAudited(); if (!isAudited && exception.requiresAuditing()) { EventDetails eventDetails = new EventDetails( downstream_uri, exception.getUri().orElse(URI.create("uri-not-present")).toASCIIString()); eventSinkMessageSender.audit( exception, exception.getErrorId(), sessionId.orElse(SessionId.NO_SESSION_CONTEXT_IN_ERROR), eventDetails); isAudited = true; } return isAudited; } @Inject  ExceptionAuditor(EventSinkMessageSender eventSinkMessageSender); boolean auditException(ApplicationException exception, Optional<SessionId> sessionId);  }### Answer:
@Test public void shouldAuditUnauditedException() throws Exception { DateTime expectedTimestamp = DateTime.now(); DateTimeFreezer.freezeTime(expectedTimestamp); final UUID errorId = UUID.randomUUID(); ApplicationException exception = createUnauditedException( ExceptionType.DUPLICATE_SESSION, errorId, URI.create("/some-uri") ); exceptionAuditor.auditException(exception, Optional.of(SESSION_ID)); ArgumentCaptor<EventDetails> argumentCaptor = ArgumentCaptor.forClass(EventDetails.class); verify(eventSinkMessageSender).audit(eq(exception), eq(errorId), eq(SESSION_ID), argumentCaptor.capture()); final EventDetails event = argumentCaptor.getValue(); assertThat(event.getKey()).isEqualTo(downstream_uri); assertThat(event.getValue()).isEqualTo(exception.getUri().get().toASCIIString()); }
@Test public void shouldNotAuditAlreadyAuditedException() throws Exception { final UUID errorId = UUID.randomUUID(); ApplicationException exception = createAuditedException(ExceptionType.DUPLICATE_SESSION, errorId); exceptionAuditor.auditException(exception, Optional.of(SESSION_ID)); verify(eventSinkMessageSender, never()).audit( any(Exception.class), any(UUID.class), any(SessionId.class), any(EventDetails.class) ); }
@Test public void shouldNotAuditUnauditedExceptionIfItDoesNotRequireAuditing() { ApplicationException exception = createUnauditedExceptionThatShouldNotBeAudited(); exceptionAuditor.auditException(exception, Optional.of(SESSION_ID)); verify(eventSinkMessageSender, never()).audit(any(Exception.class), any(UUID.class), any(SessionId.class), any(EventDetails.class)); }
@Test public void shouldAuditWithNoSessionContextIfSessionIdIsNotPresent() { final UUID errorId = UUID.randomUUID(); ApplicationException exception = createUnauditedException( ExceptionType.DUPLICATE_SESSION, errorId, URI.create("/some-uri") ); exceptionAuditor.auditException(exception, Optional.empty()); verify(eventSinkMessageSender).audit(eq(exception), eq(errorId), eq(SessionId.NO_SESSION_CONTEXT_IN_ERROR), any(EventDetails.class)); }