|
| 1 | +/* |
| 2 | + * Copyright 2020 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package org.springframework.data.util; |
| 17 | + |
| 18 | +import static org.assertj.core.api.Assertions.*; |
| 19 | + |
| 20 | +import java.util.Arrays; |
| 21 | +import java.util.Iterator; |
| 22 | +import java.util.List; |
| 23 | +import java.util.stream.Collectors; |
| 24 | +import java.util.stream.Stream; |
| 25 | + |
| 26 | +import org.junit.jupiter.api.Test; |
| 27 | + |
| 28 | +/** |
| 29 | + * Unit tests for {@link CloseableIterator}. |
| 30 | + * |
| 31 | + * @author Mark Paluch |
| 32 | + */ |
| 33 | +class CloseableIteratorUnitTests { |
| 34 | + |
| 35 | + @Test // DATACMNS-1637 |
| 36 | + void shouldCreateStream() { |
| 37 | + |
| 38 | + CloseableIteratorImpl<String> iterator = new CloseableIteratorImpl<>(Arrays.asList("1", "2", "3").iterator()); |
| 39 | + |
| 40 | + List<String> collection = iterator.stream().map(it -> "hello " + it).collect(Collectors.toList()); |
| 41 | + |
| 42 | + assertThat(collection).contains("hello 1", "hello 2", "hello 3"); |
| 43 | + assertThat(iterator.closed).isFalse(); |
| 44 | + } |
| 45 | + |
| 46 | + @Test // DATACMNS-1637 |
| 47 | + void closeStreamShouldCloseIterator() { |
| 48 | + |
| 49 | + CloseableIteratorImpl<String> iterator = new CloseableIteratorImpl<>(Arrays.asList("1", "2", "3").iterator()); |
| 50 | + |
| 51 | + try (Stream<String> stream = iterator.stream()) { |
| 52 | + assertThat(stream.findFirst()).hasValue("1"); |
| 53 | + } |
| 54 | + |
| 55 | + assertThat(iterator.closed).isTrue(); |
| 56 | + } |
| 57 | + |
| 58 | + static class CloseableIteratorImpl<T> implements CloseableIterator<T> { |
| 59 | + |
| 60 | + private final Iterator<T> delegate; |
| 61 | + private boolean closed = false; |
| 62 | + |
| 63 | + CloseableIteratorImpl(Iterator<T> delegate) { |
| 64 | + this.delegate = delegate; |
| 65 | + } |
| 66 | + |
| 67 | + @Override |
| 68 | + public void close() { |
| 69 | + closed = true; |
| 70 | + } |
| 71 | + |
| 72 | + @Override |
| 73 | + public boolean hasNext() { |
| 74 | + return delegate.hasNext(); |
| 75 | + } |
| 76 | + |
| 77 | + @Override |
| 78 | + public T next() { |
| 79 | + return delegate.next(); |
| 80 | + } |
| 81 | + } |
| 82 | +} |
0 commit comments