diff --git a/src/test/java/option/OptionalExample.java b/src/test/java/option/OptionalExample.java index db18993..accedbd 100644 --- a/src/test/java/option/OptionalExample.java +++ b/src/test/java/option/OptionalExample.java @@ -2,10 +2,13 @@ import org.junit.Test; +import java.util.NoSuchElementException; import java.util.Optional; import java.util.concurrent.ThreadLocalRandom; import java.util.function.Function; +import java.util.function.Predicate; +import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; public class OptionalExample { @@ -52,7 +55,105 @@ public void map() { private Optional getOptional() { return ThreadLocalRandom.current().nextBoolean() - ? Optional.empty() - : Optional.of("abc"); + ? Optional.empty() + : Optional.of("abc"); + } + + @Test + public void orElseGet() throws Exception { + + Optional optional = getOptional(); + + String other = "other"; + + String expected = optional.orElseGet(() -> other); + + String actual = optional.isPresent() ? optional.get() : other; + + assertEquals(expected, actual); + + } + + @Test + public void orElse() throws Exception { + + Optional optional = getOptional(); + + String other = "other"; + + String expected = optional.orElse(other); + + String actual = optional.isPresent() ? optional.get() : other; + + assertEquals(expected, actual); + + } + + + @Test + public void orElseTrow() throws Exception { + boolean isOptionalTrow = false; + String extended = ""; + + Optional optional = getOptional(); + try { + extended = optional.orElseThrow(NoSuchElementException::new); + } catch (NoSuchElementException e) { + isOptionalTrow = true; + } + + boolean isImplementationThrow = false; + + String actual = ""; + try { + if (optional.isPresent()) { + actual = optional.get(); + } else { + throw new NoSuchElementException(); + } + } catch (NoSuchElementException e) { + isImplementationThrow = true; + } + + + assertEquals(isOptionalTrow, isImplementationThrow); + + if (!isOptionalTrow) + assertEquals(extended, actual); + + } + + @Test + public void filter() throws Exception { + Optional optional = getOptional(); + + String s = "abc"; + Optional abc = optional.filter(Predicate.isEqual(s)); + + Optional actual = optional.isPresent() ? + optional.get().equals(s) ? + optional : + Optional.empty() : + Optional.empty(); + + assertEquals(abc, actual); + } + + @Test + public void flatMap() throws Exception { + + Optional optional = getOptional(); + + Optional expected = optional.flatMap(s1 -> Optional.of(s1.toCharArray())); + + Optional actual = optional.isPresent() ? + Optional.of(optional.get().toCharArray()) : + Optional.empty(); + + if (expected.isPresent()) { + assertArrayEquals(expected.get(), actual.get()); + } else { + assertEquals(expected, actual); + } } }