![JAR search and dependency download from the Maven repository](/logo.png)
it.ozimov.cirneco.hamcrest.iterable.IsIterableWithSize Maven / Gradle / Ivy
package it.ozimov.cirneco.hamcrest.iterable;
import it.ozimov.cirneco.hamcrest.iterable.utils.IterableUtils;
import org.hamcrest.Matcher;
import java.util.Collection;
import static com.google.common.base.Preconditions.checkArgument;
import static org.hamcrest.core.IsEqual.equalTo;
/**
* Does the {@linkplain Iterable} has a given size?
*
* The matcher first checks if the given {@code Iterable} is a
* {@linkplain Collection} (to get some speedup by using the {@linkplain Collection#size()} method, otherwise iterates
* all the elements to get the size of the {@code Iterable}.
*
* @since version 0.1 for JDK7
*/
public class IsIterableWithSize extends org.hamcrest.collection.IsIterableWithSize {
/**
* Creates an instance of the matcher.
*/
public IsIterableWithSize(final int size) {
super(equalTo(size));
}
/**
* Creates a matcher for {@link Iterable}s that matches when the
* examined {@link Iterable} yields an item count equal to 1
.
*
* For example:
*
assertThat(Arrays.asList("foo", "bar"), hasSizeOne())
* returns false
.
*/
public static Matcher> hasSizeOne() {
return hasSize(1);
}
/**
* Creates a matcher for {@link Iterable}s that matches when the
* examined {@link Iterable} yields an item count equal to 2
.
*
* For example:
*
assertThat(Arrays.asList("foo", "bar"), hasSizeTwo())
* returns true
.
*/
public static Matcher> hasSizeTwo() {
return hasSize(2);
}
/**
* Creates a matcher for {@link Iterable}s that matches when the
* examined {@link Iterable} yields an item count equal to 3
.
*
* For example:
*
assertThat(Arrays.asList("foo", "bar"), hasSizeThree())
* returns false
.
*/
public static Matcher> hasSizeThree() {
return hasSize(3);
}
/**
* Creates a matcher for {@link Iterable}s that matches when the
* examined {@link Iterable} yields an item count equal to 4
.
*
* For example:
*
assertThat(Arrays.asList("foo", "bar"), hasSizeFour())
* returns false
.
*/
public static Matcher> hasSizeFour() {
return hasSize(4);
}
/**
* Creates a matcher for {@link Iterable}s that matches when the
* examined {@link Iterable} yields an item count equal to 5
.
*
* For example:
*
assertThat(Arrays.asList("foo", "bar"), hasSizeFive())
* returns false
.
*/
public static Matcher> hasSizeFive() {
return hasSize(5);
}
/**
* Creates a matcher for {@link Iterable}s that matches when the
* examined {@link Iterable} yields an item count equal to size
.
*
* For example:
*
assertThat(Arrays.asList("foo", "bar"), hasSize(2))
* returns true
.
*/
public static Matcher> hasSize(final int size) {
checkArgument(size >= 0, "Size cannot be negative");
return new IsIterableWithSize(size);
}
@Override
protected Integer featureValueOf(final Iterable actual) {
return IterableUtils.size(actual);
}
}