Assert that Optional has certain value
Solution 1
You can also use AssertJ for fluent assertions
@Test
public void testThatOptionalIsNotEmpty() {
assertThat(testedMethod()).isNotEmpty();
}
@Test
public void testThatOptionalHasValue() {
assertThat(testedMethod()).hasValue("hello");
}
Solution 2
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.
Solution 3
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'
}
Solution 4
Why don’t you use isPresent()
and get()
?
Solution 5
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.
Related videos on Youtube
Matthias Braun
Build a better Stack Exchange: Codidact All code I publish on Stack Overflow and other sites of the Stack Exchange network shall be licensed under the BSD 2-Clause License: Copyright Matthias Braun All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Updated on July 09, 2022Comments
-
Matthias Braun almost 2 years
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
the returned Optional has a value (i.e., the Optional is not empty) and that
the returned value is equal to an expected value.
Let's say my tested method is
Optional<String> testedMethod(){ return Optional.of("actual value"); }
-
Ole V.V. almost 8 yearsI’d simply use
assertEquals("actual value", testedMethod().get());
It will fail with an exception if the optional is empty, which is enough for your unit test to fail,so you really need nothing more.
-
Matthias Braun almost 8 yearsThat's two assertions and results in a quite verbose unit test. I was looking for something terser.
-
Ole V.V. almost 8 yearsIf you accept
null
as another conventional representation of the absence of a value, there is alsoassertEquals("correct", opt.orElse(null));
. It’s not my personal preference, but should it be yours, go ahead. -
Ole V.V. almost 8 yearsThinking again, there’s
assertEquals(Optional.of("correct"), opt);
too. It’s terse, and while it took me a while to think of writing it, it’s OK to read, isn’t it? I would also expect it to give nice, clear messages on failures, both in the case whereopt
holds the wrong value and when it’s empty. -
shmosel almost 8 yearsI think the last way is definitely the clearest way and most "correct" approach. Consider how you would test the contents of a list or map. No reason this should be any different.
-
clausavram over 6 yearsI think it would be nicer if the terse last update from Ole V. V. got moved to the top of the answer. It's the most important part and shouldn't be last in such a long answer
-
borjab about 4 years@MatthiasBraun There is nothing bad about having two assertions if they test a single concept. I agree that it is not very terse
-
Marcos over 3 yearsIf you try to use "get()" without a "isPresent()" check, the IDE will throw a warning which is not good for me