Assert that Optional has certain value

We Are Going To Discuss About Assert that Optional has certain value. So lets Start this Java Article.

Assert that Optional has certain value

Advertisements
  1. Assert that Optional has certain value

    There are several different ways to do this, depending on your taste for clarity of test results vs. conciseness of test writing. For this answer I'll stick to “stock” Java 8 and JUnit 4 with no additional dependencies.

  2. Assert that Optional has certain value

    There are several different ways to do this, depending on your taste for clarity of test results vs. conciseness of test writing. For this answer I'll stick to “stock” Java 8 and JUnit 4 with no additional dependencies.

Solution 1

Advertisements

You can also use AssertJ for fluent assertions

@Test
public void testThatOptionalIsNotEmpty() {
    assertThat(testedMethod()).isNotEmpty();
}

@Test
public void testThatOptionalHasValue() {
    assertThat(testedMethod()).hasValue("hello");
}

Original Author Spotted Of This Content

Solution 2

Advertisements

TL;DR the best overall approach was suggested by Ole V. V.:

assertEquals(Optional.of("expected"), opt);

Other alternatives are discussed below.

There are several different ways to do this, depending on your taste for clarity of test results vs. conciseness of test writing. For this answer I’ll stick to “stock” Java 8 and JUnit 4 with no additional dependencies.

One way, as suggested in a comment by Ole V.V., is simply to write

assertEquals("expected", opt.get());

This mostly works but if the Optional is empty, then get() will throw NoSuchElementException. This in turn causes JUnit to signal an error instead of a failure, which might not be what you want. It’s also not very clear what’s going on unless you already know that get() throws NSEE in this case.

An alternative is

assertTrue(opt.isPresent() && "expected".equals(opt.get()));

This also mostly works but it doesn’t report the actual value if there’s a mismatch, which might make debugging inconvenient.

Another alternative is

assertEquals("expected", opt.orElseThrow(AssertionFailedError::new));

This gives the right failures and reports the actual value when there’s a mismatch, but it’s not very explicit about why AssertionFailedError is thrown. You might have to stare at it a while until you realize that AFE gets thrown when the Optional is empty.

Still another alternative is

assertEquals("expected", opt.orElseThrow(() -> new AssertionFailedError("empty")));

but this is starting to get verbose.

You could split this into two assertions,

assertTrue(opt.isPresent());
assertEquals("expected", opt.get());

but you had previously objected to this suggestion because of verbosity. This isn’t really terribly verbose in my opinion, but it does have some cognitive overhead since there are two separate assertions, and it relies on the second only being checked if the first succeeds. This is not incorrect but it is a bit subtle.

Finally, if you’re willing to create a bit of your own infrastructure, you could create a suitably-named subclass of AssertionFailedError and use it like this:

assertEquals("expected", opt.orElseThrow(UnexpectedEmptyOptional::new));

Finally, in another comment, Ole V. V. suggested

assertEquals(Optional.of("correct"), opt);

This works quite well, and in fact this might be the best of all.

Original Author Stuart Marks Of This Content

Solution 3

Advertisements

I use Hamcrest Optional for that:

import static com.github.npathai.hamcrestopt.OptionalMatchers.hasValue;
import org.junit.Test;

public class MyUnitTests {

  @Test
  public void testThatOptionalHasValue(){
    String expectedValue = "actual value";
    assertThat(testedMethod(), hasValue(expectedValue));
  }
}

You can add Hamcrest Optional to your dependencies by including it in your build.gradle:

dependencies {
  testCompile 'junit:junit:4.12'
  testCompile 'com.github.npathai:hamcrest-optional:1.0'
}

Original Author Stuart Marks Of This Content

Solution 4

Advertisements

Why don’t you use isPresent() and get()?

Original Author mzq Of This Content

Conclusion

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

Siddharth

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment