QueryResultSpliterator extends Spliterators.AbstractSpliterator<X> { @Override public boolean tryAdvance(Consumer<? super X> action) { try { final boolean result = resultSetSpliterator.tryAdvance(row -> mapAndApply(row, action)); if (!result) { onClose.execute(); } return result; } catch (RuntimeException e) { onClose.execute(); throw e; } } QueryResultSpliterator(Spliterator<ResultRow> resultSetSpliterator, Function<ResultRow, Optional<X>> mapper,
                           Procedure onClose); @Override boolean tryAdvance(Consumer<? super X> action); @Override void forEachRemaining(Consumer<? super X> action);  }
@Test void tryAdvancePassesResultSetValueToMapperAndThenConsumer() { when(resultSetSpliterator.tryAdvance(any())).then(invocation -> { ((Consumer<ResultRow>) invocation.getArgument(0)).accept(resultRow); return true; }); when(mapper.apply(any())).thenReturn(Optional.of("test")); sut.tryAdvance(consumer); verify(mapper).apply(resultRow); verify(consumer).accept("test"); }
@Test void tryAdvanceReturnsTrueWhenResultSetSpliteratorReturnsTrue() { when(resultSetSpliterator.tryAdvance(any())).then(invocation -> { ((Consumer<ResultRow>) invocation.getArgument(0)).accept(resultRow); return true; }); when(mapper.apply(any())).thenReturn(Optional.of("test")); assertTrue(sut.tryAdvance(consumer)); }
@Test void tryAdvanceReturnsFalseWhenResultSetSpliteratorReturnsFalse() { when(resultSetSpliterator.tryAdvance(any())).then(invocation -> { ((Consumer<ResultRow>) invocation.getArgument(0)).accept(resultRow); return false; }); when(mapper.apply(any())).thenReturn(Optional.of("test")); assertFalse(sut.tryAdvance(consumer)); }
@Test void tryAdvanceInvokesClosingProcedureWhenResultSetSpliteratorReturnsFalse() { when(resultSetSpliterator.tryAdvance(any())).then(invocation -> { ((Consumer<ResultRow>) invocation.getArgument(0)).accept(resultRow); return false; }); when(mapper.apply(any())).thenReturn(Optional.of("test")); sut.tryAdvance(consumer); verify(closer).execute(); }
@Test void tryAdvanceInvokesClosingProcedureWhenConsumerThrowsException() { when(resultSetSpliterator.tryAdvance(any())).then(invocation -> { ((Consumer<ResultRow>) invocation.getArgument(0)).accept(resultRow); return true; }); when(mapper.apply(any())).thenReturn(Optional.of("test")); doThrow(OWLPersistenceException.class).when(consumer).accept(anyString()); assertThrows(OWLPersistenceException.class, () -> sut.tryAdvance(consumer)); verify(closer).execute(); }
@Test void tryAdvanceDoesNotInvokeConsumerWhenMapperReturnsEmptyOptional() { when(resultSetSpliterator.tryAdvance(any())).then(invocation -> { ((Consumer<ResultRow>) invocation.getArgument(0)).accept(resultRow); return true; }); when(mapper.apply(any())).thenReturn(Optional.empty()); assertTrue(sut.tryAdvance(consumer)); verify(consumer, never()).accept(any()); }