SystemUserUtil { public JsonEnvelope asEnvelopeWithSystemUserId(final JsonEnvelope envelope) { final UUID sysUserId = systemUserProvider.getContextSystemUserId() .orElseThrow(() -> new IllegalStateException("System userId not found")); return envelopeFrom( metadataFrom(envelope.metadata()) .withUserId(sysUserId.toString()), envelope.payload()); }  JsonEnvelope asEnvelopeWithSystemUserId(final JsonEnvelope envelope);  }
@Test public void shouldReturnEnvelopeWithSystemUserId() throws Exception { final UUID sysUserId = randomUUID(); when(systemUserProvider.getContextSystemUserId()).thenReturn(Optional.of(sysUserId)); final UUID id = randomUUID(); final String name = "name456"; final JsonEnvelope returnedEnvelope = systemUserUtil.asEnvelopeWithSystemUserId( envelopeFrom(metadataBuilder() .withId(id) .withName(name) .withUserId("someIdToBeReplaced"), createObjectBuilder().add("numName", BigDecimal.valueOf(123))) ); assertThat(returnedEnvelope.metadata().id(), is(id)); assertThat(returnedEnvelope.metadata().name(), is(name)); assertThat(returnedEnvelope.metadata().userId(), contains(sysUserId.toString())); assertThat(returnedEnvelope.payloadAsJsonObject().getInt("numName"), is(123)); }
@Test(expected = IllegalStateException.class) public void shouldThrowExceptionIfSystemUserNotFound() throws Exception { when(systemUserProvider.getContextSystemUserId()).thenReturn(Optional.empty()); systemUserUtil.asEnvelopeWithSystemUserId(envelopeFrom(metadataBuilder().withId(randomUUID()).withName("name"), createObjectBuilder())); }