|
| 1 | +package com.baeldung.java.listInitialization; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Arrays; |
| 5 | +import java.util.List; |
| 6 | +import java.util.stream.Collectors; |
| 7 | +import java.util.stream.Stream; |
| 8 | + |
| 9 | +import lombok.extern.java.Log; |
| 10 | + |
| 11 | +import org.junit.Assert; |
| 12 | +import org.junit.Rule; |
| 13 | +import org.junit.Test; |
| 14 | +import org.junit.rules.ExpectedException; |
| 15 | + |
| 16 | +@Log |
| 17 | +public class ListInitializationUnitTest { |
| 18 | + |
| 19 | + @Rule |
| 20 | + public ExpectedException exception = ExpectedException.none(); |
| 21 | + |
| 22 | + @Test |
| 23 | + public void givenAnonymousInnerClass_thenInitialiseList() { |
| 24 | + List<String> cities = new ArrayList() { |
| 25 | + // Inside declaration of the subclass |
| 26 | + |
| 27 | + // You can have multiple initializer block |
| 28 | + { |
| 29 | + log.info("Inside the first initializer block."); |
| 30 | + } |
| 31 | + |
| 32 | + { |
| 33 | + log.info("Inside the second initializer block."); |
| 34 | + add("New York"); |
| 35 | + add("Rio"); |
| 36 | + add("Tokyo"); |
| 37 | + } |
| 38 | + }; |
| 39 | + |
| 40 | + Assert.assertTrue(cities.contains("New York")); |
| 41 | + } |
| 42 | + |
| 43 | + @Test |
| 44 | + public void givenArraysAsList_thenInitialiseList() { |
| 45 | + List<String> list = Arrays.asList("foo", "bar"); |
| 46 | + |
| 47 | + Assert.assertTrue(list.contains("foo")); |
| 48 | + } |
| 49 | + |
| 50 | + @Test |
| 51 | + public void givenArraysAsList_whenAdd_thenUnsupportedException() { |
| 52 | + List<String> list = Arrays.asList("foo", "bar"); |
| 53 | + |
| 54 | + exception.expect(UnsupportedOperationException.class); |
| 55 | + list.add("baz"); |
| 56 | + } |
| 57 | + |
| 58 | + @Test |
| 59 | + public void givenArrayAsList_whenCreated_thenShareReference() { |
| 60 | + String[] array = { "foo", "bar" }; |
| 61 | + List<String> list = Arrays.asList(array); |
| 62 | + array[0] = "baz"; |
| 63 | + Assert.assertEquals("baz", list.get(0)); |
| 64 | + } |
| 65 | + |
| 66 | + @Test |
| 67 | + public void givenStream_thenInitializeList() { |
| 68 | + List<String> list = Stream.of("foo", "bar") |
| 69 | + .collect(Collectors.toList()); |
| 70 | + |
| 71 | + Assert.assertTrue(list.contains("foo")); |
| 72 | + } |
| 73 | +} |
0 commit comments