1/* 2 * Copyright (C) 2016 The Android Open Source Project 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 * http://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 17package libcore.java.util; 18 19import junit.framework.TestCase; 20 21import java.io.IOException; 22import java.util.NoSuchElementException; 23import java.util.OptionalInt; 24import java.util.concurrent.atomic.AtomicInteger; 25import java.util.function.IntConsumer; 26import java.util.function.IntSupplier; 27import java.util.function.Supplier; 28 29public class OptionalIntTest extends TestCase { 30 public void testEmpty_sameInstance() { 31 assertSame(OptionalInt.empty(), OptionalInt.empty()); 32 } 33 34 public void testGet() { 35 assertEquals(56, OptionalInt.of(56).getAsInt()); 36 37 try { 38 OptionalInt.empty().getAsInt(); 39 fail(); 40 } catch (NoSuchElementException nsee) { 41 } 42 } 43 44 public void testIsPresent() { 45 assertTrue(OptionalInt.of(56).isPresent()); 46 assertFalse(OptionalInt.empty().isPresent()); 47 } 48 49 public void testIfPresent() { 50 IntConsumer alwaysFails = value -> fail(); 51 OptionalInt.empty().ifPresent(alwaysFails); 52 53 final AtomicInteger reference = new AtomicInteger(); 54 IntConsumer recorder = value -> reference.set(value);; 55 OptionalInt.of(56).ifPresent(recorder); 56 assertEquals(56, reference.get()); 57 } 58 59 public void testOrElse() { 60 assertEquals(57, OptionalInt.empty().orElse(57)); 61 assertEquals(56, OptionalInt.of(56).orElse(57)); 62 } 63 64 public void testOrElseGet() { 65 IntSupplier alwaysFails = () -> { fail(); return 57; }; 66 assertEquals(56, OptionalInt.of(56).orElseGet(alwaysFails)); 67 68 IntSupplier supplies57 = () -> 57; 69 assertEquals(57, OptionalInt.empty().orElseGet(supplies57)); 70 } 71 72 public void testOrElseThrow() throws IOException { 73 final IOException bar = new IOException("bar"); 74 75 Supplier<IOException> barSupplier = () -> bar; 76 assertEquals(57, OptionalInt.of(57).orElseThrow(barSupplier)); 77 78 try { 79 OptionalInt.empty().orElseThrow(barSupplier); 80 fail(); 81 } catch (IOException expected) { 82 assertSame(bar, expected); 83 } 84 } 85 86 public void testEquals() { 87 assertEquals(OptionalInt.empty(), OptionalInt.empty()); 88 assertEquals(OptionalInt.of(56), OptionalInt.of(56)); 89 assertFalse(OptionalInt.empty().equals(OptionalInt.of(56))); 90 assertFalse(OptionalInt.of(57).equals(OptionalInt.of(56))); 91 } 92 93 public void testHashCode() { 94 assertEquals(Integer.hashCode(57), OptionalInt.of(57).hashCode()); 95 } 96} 97