I have a Java method that returns an Optional. I'd like to write an easy-to-read unit test for it that asserts that
the returned Optional has a value (i.e., the Optional is not empty) and that
the returned value is equal to an expected value.
Let's say my tested method is
Optional<String> testedMethod(){ return Optional.of("actual value"); }
Checking the presence of a valueisPresent() method returns true if the Optional contains a non-null value, otherwise it returns false. ifPresent() method allows you to pass a Consumer function that is executed if a value is present inside the Optional object. It does nothing if the Optional is empty.
assertEquals: Asserts that two objects are equal. assertSame: Asserts that two objects refer to the same object. In other words. assertEquals: uses the equals() method, or if no equals() method was overridden, compares the reference between the 2 objects.
In assertTrue, you are asserting that the expression is true. If it is not, then it will display the message and the assertion will fail. In assertFalse, you are asserting that an expression evaluates to false. If it is not, then the message is displayed and the assertion fails.
You can also use AssertJ for fluent assertions
@Test public void testThatOptionalIsNotEmpty() { assertThat(testedMethod()).isNotEmpty(); } @Test public void testThatOptionalHasValue() { assertThat(testedMethod()).hasValue("hello"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With