Reusable assertions for Iterable s. @author Alex Ruiz @author Yvonne Wang @author Maciej Jaskowski @author Nicolas François @author Joel Costigliola
| 71 | * @author Joel Costigliola |
| 72 | */ |
| 73 | public class Iterables { |
| 74 | |
| 75 | private static final Iterables INSTANCE = new Iterables(); |
| 76 | private final ComparisonStrategy comparisonStrategy; |
| 77 | @VisibleForTesting |
| 78 | Failures failures = Failures.instance(); |
| 79 | @VisibleForTesting |
| 80 | Conditions conditions = Conditions.instance(); |
| 81 | |
| 82 | /** |
| 83 | * Returns the singleton instance of this class based on {@link StandardComparisonStrategy}. |
| 84 | * |
| 85 | * @return the singleton instance of this class based on {@link StandardComparisonStrategy}. |
| 86 | */ |
| 87 | public static Iterables instance() { |
| 88 | return INSTANCE; |
| 89 | } |
| 90 | |
| 91 | @VisibleForTesting |
| 92 | Iterables() { |
| 93 | this(StandardComparisonStrategy.instance()); |
| 94 | } |
| 95 | |
| 96 | public Iterables(ComparisonStrategy comparisonStrategy) { |
| 97 | this.comparisonStrategy = comparisonStrategy; |
| 98 | } |
| 99 | |
| 100 | @VisibleForTesting |
| 101 | public Comparator<?> getComparator() { |
| 102 | if (comparisonStrategy instanceof ComparatorBasedComparisonStrategy) { |
| 103 | return ((ComparatorBasedComparisonStrategy) comparisonStrategy).getComparator(); |
| 104 | } |
| 105 | return null; |
| 106 | } |
| 107 | |
| 108 | /** |
| 109 | * Asserts that the given <code>{@link Iterable}</code> is {@code null} or empty. |
| 110 | * |
| 111 | * @param info contains information about the assertion. |
| 112 | * @param actual the given {@code Iterable}. |
| 113 | * @throws AssertionError if the given {@code Iterable} is not {@code null} *and* contains one or more elements. |
| 114 | */ |
| 115 | public void assertNullOrEmpty(AssertionInfo info, Iterable<?> actual) { |
| 116 | if (actual == null || isNullOrEmpty(actual)) { |
| 117 | return; |
| 118 | } |
| 119 | throw failures.failure(info, shouldBeNullOrEmpty(actual)); |
| 120 | } |
| 121 | |
| 122 | /** |
| 123 | * Asserts that the given {@code Iterable} is empty. |
| 124 | * |
| 125 | * @param info contains information about the assertion. |
| 126 | * @param actual the given {@code Iterable}. |
| 127 | * @throws AssertionError if the given {@code Iterable} is {@code null}. |
| 128 | * @throws AssertionError if the given {@code Iterable} is not empty. |
| 129 | */ |
| 130 | public void assertEmpty(AssertionInfo info, Iterable<?> actual) { |