ArchivingService { public Mono<DocumentEntity> archiveDocument(final DocumentArchivingContext documentArchivingContext) { return documentCreationContextFactory.newContext(documentArchivingContext) .flatMap(documentEntityFactory::newDocumentEntity) .doOnNext(documentEntity -> vaultDocumentStorage.persistDocument(documentEntity, documentArchivingContext.getContent())) .doOnError(throwable -> handleError(throwable, documentArchivingContext)) .retryWhen( Retry.indefinitely() .filter(throwable -> !isDuplicateIndexError(throwable)) ); }  Mono<DocumentEntity> archiveDocument(final DocumentArchivingContext documentArchivingContext);  }
@Test void testRetryWhenErrorHappensWhilePersisting() { final DocumentArchivingContext documentArchivingContext = createDocumentArchivingContext(); final DocumentCreationContext documentCreationContext = DocumentCreationContext.builder() .build(); when(documentCreationContextFactory.newContext(documentArchivingContext)) .thenReturn(Mono.just(documentCreationContext)); final DocumentEntity documentEntity = DocumentEntity.builder() .build(); when(documentEntityFactory.newDocumentEntity(documentCreationContext)) .thenReturn(Mono.just(documentEntity)); final MongoWriteException mongoWriteException = mock(MongoWriteException.class); when(mongoWriteException.getMessage()).thenReturn("E11000 duplicate key error"); doThrow(new RuntimeException("Test exception"), mongoWriteException) .when(vaultDocumentStorage).persistDocument(any(), any()); final Mono<DocumentEntity> result = underTest.archiveDocument(documentArchivingContext); StepVerifier.create(result) .verifyError(MongoWriteException.class); verify(vaultDocumentStorage, times(2)).persistDocument(any(), any()); }
@Test void testWhenPersistingAValidDocument() { final DocumentArchivingContext documentArchivingContext = createDocumentArchivingContext(); final DocumentCreationContext documentCreationContext = DocumentCreationContext.builder() .build(); when(documentCreationContextFactory.newContext(documentArchivingContext)) .thenReturn(Mono.just(documentCreationContext)); final DocumentEntity documentEntity = DocumentEntity.builder() .build(); when(documentEntityFactory.newDocumentEntity(documentCreationContext)) .thenReturn(Mono.just(documentEntity)); final Mono<DocumentEntity> result = underTest.archiveDocument(documentArchivingContext); StepVerifier.create(result) .consumeNextWith(documentEntity1 -> assertThat(documentEntity1, is(documentEntity))) .verifyComplete(); verify(vaultDocumentStorage).persistDocument(eq(documentEntity), documentContent.capture()); assertThat(documentContent.getValue(), is(CONTENT)); verify(documentCreationContextFactory).newContext(documentArchivingContext); verify(documentEntityFactory).newDocumentEntity(documentCreationContext); }