From 157d7ee61c95365176fb88933c8fc1ea1f9c1217 Mon Sep 17 00:00:00 2001 From: lucaCambi77 Date: Sun, 14 Nov 2021 11:09:48 +0100 Subject: [PATCH] [BAEL-5211] - How to test a Java Optional (#11417) * feat: add how to test an optional * fix: review comments * fix: static final naming convention * fix: optional equals assertion --- .../baeldung/optional/OptionalUnitTest.java | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 testing-modules/testing-assertions/src/test/java/com/baeldung/optional/OptionalUnitTest.java diff --git a/testing-modules/testing-assertions/src/test/java/com/baeldung/optional/OptionalUnitTest.java b/testing-modules/testing-assertions/src/test/java/com/baeldung/optional/OptionalUnitTest.java new file mode 100644 index 0000000000..351b3dd3e0 --- /dev/null +++ b/testing-modules/testing-assertions/src/test/java/com/baeldung/optional/OptionalUnitTest.java @@ -0,0 +1,58 @@ +package com.baeldung.optional; + +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class OptionalUnitTest { + + private static final String OPTIONAL_RETURN_VALUE = "optionalReturnValue"; + + @Test + public void givenOptionalWithValue_whenAssertThatIsNotEmpty_thenOk() { + assertThat(Optional.of(OPTIONAL_RETURN_VALUE)).isNotEmpty(); + } + + @Test + public void givenOptionalWithValue_whenAssertThatHasValue_thenOk() { + assertThat(Optional.of(OPTIONAL_RETURN_VALUE)).hasValue(OPTIONAL_RETURN_VALUE); + } + + @Test + public void givenOptionalWithValue_whenAssertEqualsOptionalObject_thenOk() { + Optional expected = Optional.of(OPTIONAL_RETURN_VALUE); + Optional actual = Optional.of(OPTIONAL_RETURN_VALUE); + assertEquals(expected, actual); + } + + @Test + public void givenOptionalWithValue_whenAssertEqualsGet_thenOk() { + Optional optional = Optional.of(OPTIONAL_RETURN_VALUE); + assertEquals(OPTIONAL_RETURN_VALUE, optional.get()); + } + + @Test + public void givenOptionalWithValue_whenIsPresentAndGetSplit_thenOk() { + Optional optional = Optional.of(OPTIONAL_RETURN_VALUE); + + assertTrue(optional.isPresent()); + assertEquals(OPTIONAL_RETURN_VALUE, optional.get()); + } + + @Test + public void givenEmptyOptional_whenAssertThatIsEmpty_thenOk() { + Optional emptyOptional = Optional.empty(); + assertThat(emptyOptional).isEmpty(); + } + + @Test + public void givenEmptyOptional_whenAssertIsNotPresent_thenOk() { + Optional emptyOptional = Optional.empty(); + assertFalse(emptyOptional.isPresent()); + } +}