|
| 1 | +package com.baeldung.nullsafecollectionstreams; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | +import java.util.Collection; |
| 5 | +import java.util.Iterator; |
| 6 | +import java.util.stream.Stream; |
| 7 | +import org.junit.Test; |
| 8 | +import static org.junit.Assert.*; |
| 9 | + |
| 10 | +public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest { |
| 11 | + |
| 12 | + private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance = |
| 13 | + new NullSafeCollectionStreamsUsingJava8OptionalContainer(); |
| 14 | + @Test |
| 15 | + public void whenCollectionIsNull_thenExpectAnEmptyStream() { |
| 16 | + Collection<String> collection = null; |
| 17 | + Stream<String> expResult = Stream.empty(); |
| 18 | + Stream<String> result = instance.collectionAsStream(collection); |
| 19 | + assertStreamEquals(expResult, result); |
| 20 | + } |
| 21 | + |
| 22 | + @Test |
| 23 | + public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() { |
| 24 | + Collection<String> collection = Arrays.asList("a", "b", "c"); |
| 25 | + Stream<String> expResult = Arrays.stream(new String[] { "a", "b", "c" }); |
| 26 | + Stream<String> result = instance.collectionAsStream(collection); |
| 27 | + assertStreamEquals(expResult, result); |
| 28 | + } |
| 29 | + |
| 30 | + private static void assertStreamEquals(Stream<?> s1, Stream<?> s2) { |
| 31 | + Iterator<?> iter1 = s1.iterator(), iter2 = s2.iterator(); |
| 32 | + while (iter1.hasNext() && iter2.hasNext()) |
| 33 | + assertEquals(iter1.next(), iter2.next()); |
| 34 | + assert !iter1.hasNext() && !iter2.hasNext(); |
| 35 | + } |
| 36 | + |
| 37 | +} |
0 commit comments