From 71ef6b2a431d8395b41ffa1387ff650a4f0b35ae Mon Sep 17 00:00:00 2001 From: Mohamed Sanaulla Date: Thu, 10 Aug 2017 04:02:17 +0300 Subject: [PATCH] code for Java 9 Objects API (#2408) --- .../language/Java9ObjectsAPIUnitTest.java | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java new file mode 100644 index 0000000000..a174e519ab --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java @@ -0,0 +1,72 @@ +package com.baeldung.java9.language; + +import org.junit.Test; + +import java.util.Collections; +import java.util.List; +import java.util.Objects; + +import static org.hamcrest.Matchers.*; +import static org.hamcrest.MatcherAssert.assertThat; + +public class Java9ObjectsAPIUnitTest { + + @Test + public void givenNullObject_whenRequireNonNullElse_thenElse(){ + assertThat(Objects.requireNonNullElse(null, Collections.EMPTY_LIST), + is(Collections.EMPTY_LIST)); + } + + @Test + public void givenObject_whenRequireNonNullElse_thenObject(){ + assertThat(Objects.requireNonNullElse(List.of("item1", "item2"), + Collections.EMPTY_LIST), is(List.of("item1", "item2"))); + } + + @Test + public void givenObject_whenRequireNonNullElseGet_thenObject(){ + assertThat(Objects.requireNonNullElseGet(null, List::of), + is(List.of())); + } + + @Test + public void givenNumber_whenInvokeCheckIndex_thenNumber(){ + int length = 5; + + assertThat(Objects.checkIndex(4, length), is(4)); + + try{ + Objects.checkIndex(5, length); + }catch(Exception ex){ + assertThat(ex, instanceOf(IndexOutOfBoundsException.class)); + } + } + + @Test + public void givenSubRange_whenCheckFromToIndex_thenNumber(){ + int length = 6; + + assertThat(Objects.checkFromToIndex(2,length,length), is(2)); + + try{ + Objects.checkFromToIndex(2,7,length); + }catch(Exception ex){ + assertThat(ex, instanceOf(IndexOutOfBoundsException.class)); + } + } + + @Test + public void giveSubRange_whenCheckFromIndexSize_thenNumber(){ + int length = 6; + + assertThat(Objects.checkFromToIndex(2,5,length), is(2)); + + try{ + Objects.checkFromToIndex(2,6,length); + }catch(Exception ex){ + assertThat(ex, instanceOf(IndexOutOfBoundsException.class)); + } + } + + +}