|
| 1 | +/* |
| 2 | + * To change this license header, choose License Headers in Project Properties. |
| 3 | + * To change this template file, choose Tools | Templates |
| 4 | + * and open the template in the editor. |
| 5 | + */ |
| 6 | +package com.baeldung.nullsafecollectionstreams; |
| 7 | + |
| 8 | +import java.util.Arrays; |
| 9 | +import java.util.Collection; |
| 10 | +import java.util.Iterator; |
| 11 | +import java.util.stream.Stream; |
| 12 | +import org.junit.After; |
| 13 | +import org.junit.AfterClass; |
| 14 | +import org.junit.Before; |
| 15 | +import org.junit.BeforeClass; |
| 16 | +import org.junit.Test; |
| 17 | +import static org.junit.Assert.*; |
| 18 | + |
| 19 | +/** |
| 20 | + * |
| 21 | + * @author Kwaje Anthony <kwajeanthony@gmail.com> |
| 22 | + */ |
| 23 | +public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest { |
| 24 | + |
| 25 | + private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance = |
| 26 | + new NullSafeCollectionStreamsUsingJava8OptionalContainer(); |
| 27 | + |
| 28 | + @Test |
| 29 | + public void whenCollectionIsNull_thenExpectAnEmptyStream() { |
| 30 | + Collection<String> collection = null; |
| 31 | + Stream<String> expResult = Stream.empty(); |
| 32 | + Stream<String> result = instance.collectionAsStream(collection); |
| 33 | + assertStreamEquals(expResult, result); |
| 34 | + |
| 35 | + } |
| 36 | + |
| 37 | + @Test |
| 38 | + public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() { |
| 39 | + |
| 40 | + Collection<String> collection = Arrays.asList("a", "b", "c"); |
| 41 | + Stream<String> expResult = Arrays.stream(new String[] { "a", "b", "c" }); |
| 42 | + Stream<String> result = instance.collectionAsStream(collection); |
| 43 | + assertStreamEquals(expResult, result); |
| 44 | + } |
| 45 | + |
| 46 | + private static void assertStreamEquals(Stream<?> s1, Stream<?> s2) { |
| 47 | + Iterator<?> iter1 = s1.iterator(), iter2 = s2.iterator(); |
| 48 | + while (iter1.hasNext() && iter2.hasNext()) |
| 49 | + assertEquals(iter1.next(), iter2.next()); |
| 50 | + assert !iter1.hasNext() && !iter2.hasNext(); |
| 51 | + } |
| 52 | + |
| 53 | +} |
0 commit comments