Assert that Optional has certain value

前端 未结 5 2150
南笙
南笙 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: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.

提交回复
热议问题