Reputation: 34393
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");
}
Upvotes: 57
Views: 108525
Reputation: 4091
You can also use AssertJ for fluent assertions
@Test
public void testThatOptionalIsNotEmpty() {
assertThat(testedMethod()).isNotEmpty();
}
@Test
public void testThatOptionalHasValue() {
assertThat(testedMethod()).hasValue("hello");
}
Upvotes: 62
Reputation: 887
I prefer applying .orElse(null) to the returned Optional before asserting it.
The method assertEquals can be used with an Optional containing the expected value (or assertThat(result).isEqualTo(expected) when using FEST assertions).
But using .orElse has the benefit that the result has the correct type and that allows to do all checks that you might want to do also if the method wasn't an optional:
Using an Optional of the expected value doesn't allow all those things.
Upvotes: 1
Reputation: 132510
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.
Upvotes: 45
Reputation: 4121
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.
Upvotes: 1
Reputation: 34393
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'
}
Upvotes: 5