Assert that Optional has certain value

前端 未结 5 2130
南笙
南笙 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条回答
  •  小鲜肉
    小鲜肉 (楼主)
    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'
    }
    

提交回复
热议问题