Assert that Optional has certain value

前端 未结 5 2128
南笙
南笙 2020-12-29 19:54

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.

相关标签:
5条回答
  • 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.

    0 讨论(0)
  • 2020-12-29 20:22

    The below approach uses the fact that you can specify a default return for an optional. So your test method could be something like this:

    @test
    public void testThatOptionalHasValue() {
        String expectedValue = "actual value";
        String actualValue = Optional.ofNullable(testedMethod()).orElse("not " + expectedValue);
        assertEquals("The values are not the same", expectedValue, actualValue);
    }
    

    This guarentees that if your method returns null, then the result can not be the same as the expected value.

    0 讨论(0)
  • 2020-12-29 20:22

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

    0 讨论(0)
  • 2020-12-29 20:35

    You can also use AssertJ for fluent assertions

    @Test
    public void testThatOptionalIsNotEmpty() {
        assertThat(testedMethod()).isNotEmpty();
    }
    
    @Test
    public void testThatOptionalHasValue() {
        assertThat(testedMethod()).hasValue("hello");
    }
    
    0 讨论(0)
  • 2020-12-29 20:36

    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'
    }
    
    0 讨论(0)
提交回复
热议问题