Advertisement
Guest User

Untitled

a guest
May 5th, 2015
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. import org.hamcrest.Description;
  2. import org.hamcrest.Factory;
  3. import org.hamcrest.Matcher;
  4. import org.hamcrest.TypeSafeDiagnosingMatcher;
  5.  
  6. import java.util.Optional;
  7.  
  8. import static org.hamcrest.core.IsEqual.equalTo;
  9.  
  10. public class OptionalWithValue<T> extends TypeSafeDiagnosingMatcher<Optional<? extends T>> {
  11.  
  12. @Factory
  13. public static <T> Matcher<Optional<? extends T>> optionalWithValue(Matcher<? super T> valueMatcher) {
  14. return new OptionalWithValue<>(valueMatcher);
  15. }
  16.  
  17. @Factory
  18. public static <T> Matcher<Optional<? extends T>> optionalWithValue(T value) {
  19. return optionalWithValue(equalTo(value));
  20. }
  21.  
  22. private final Matcher<? super T> subMatcher;
  23.  
  24. public OptionalWithValue(Matcher<? super T> subMatcher) {
  25. this.subMatcher = subMatcher;
  26. }
  27.  
  28. @Override
  29. protected boolean matchesSafely(Optional<? extends T> item, Description mismatchDescription) {
  30. if (!item.isPresent()) {
  31. mismatchDescription.appendText("an empty optional");
  32. return false;
  33. }
  34.  
  35. boolean matches = subMatcher.matches(item.get());
  36. if (!matches) {
  37. subMatcher.describeMismatch(item.get(), mismatchDescription);
  38. }
  39.  
  40. return matches;
  41. }
  42.  
  43. @Override
  44. public void describeTo(Description description) {
  45. description.appendText("optional with value ");
  46. subMatcher.describeTo(description);
  47. }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement