Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert that Optional has certain value

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

  1. the returned Optional has a value (i.e., the Optional is not empty) and that

  2. the returned value is equal to an expected value.

Let's say my tested method is

Optional<String> testedMethod(){   return Optional.of("actual value"); } 
like image 373
Matthias Braun Avatar asked Aug 15 '16 12:08

Matthias Braun


People also ask

How do you know if optional has 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.

What is assert assertSame?

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.

What is assert assertFalse?

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.


1 Answers

You can also use AssertJ for fluent assertions

@Test public void testThatOptionalIsNotEmpty() {     assertThat(testedMethod()).isNotEmpty(); }  @Test public void testThatOptionalHasValue() {     assertThat(testedMethod()).hasValue("hello"); } 
like image 98
Spotted Avatar answered Sep 23 '22 04:09

Spotted