Skip to content

Commit 07fda5d

Browse files
author
neildunn
committed
Added IsCollectionOnlyContaining to close issue 5
1 parent 43f7d8b commit 07fda5d

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

CHANGES.txt

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@
44
generics bug in hasKey and hasValue static factories previously declared
55
in IsMapContaining (ngd)
66

7+
* Added IsCollectionOnlyContaining which matches collections with
8+
items only matching a specified item. E.g onlyContains(3,4,5) or
9+
onlyContains(lessThan(9))
10+
711
== Version 1.1: Released Jun 30 2007 ==
812

913
* Hamcrest Generator now includes JavaDoc and parameter names in generated code
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package org.hamcrest.collection;
2+
3+
import static org.hamcrest.core.AnyOf.anyOf;
4+
import static org.hamcrest.core.IsEqual.equalTo;
5+
6+
import java.util.ArrayList;
7+
import java.util.Collection;
8+
9+
import org.hamcrest.Description;
10+
import org.hamcrest.Factory;
11+
import org.hamcrest.Matcher;
12+
import org.hamcrest.TypeSafeMatcher;
13+
14+
/**
15+
* Matches collections that only contain elements that satisfy a given matcher.
16+
* </p>
17+
* For example <pre>[1,2,3]</pre> satisfies onlyContains(lessThan(4))
18+
*
19+
* @author ngd
20+
*/
21+
public class IsCollectionOnlyContaining<T> extends TypeSafeMatcher<Collection<T>> {
22+
23+
private final Matcher<T> matcher;
24+
25+
public IsCollectionOnlyContaining(Matcher<T> matcher) {
26+
this.matcher = matcher;
27+
}
28+
29+
@Override
30+
public boolean matchesSafely(Collection<T> items) {
31+
for (T item : items) {
32+
if (!matcher.matches(item)) {
33+
return false;
34+
}
35+
}
36+
return true;
37+
}
38+
39+
public void describeTo(Description description) {
40+
description
41+
.appendText("a collection containing items matching ")
42+
.appendDescriptionOf(matcher);
43+
}
44+
45+
@Factory
46+
public static <T> Matcher<Collection<T>> onlyContains(T... items) {
47+
Collection<Matcher<T>> matchers = new ArrayList<Matcher<T>>();
48+
for (T item : items) {
49+
matchers.add(equalTo(item));
50+
}
51+
return new IsCollectionOnlyContaining<T>(anyOf(matchers));
52+
}
53+
54+
@Factory
55+
public static <T> Matcher<Collection<T>> onlyContains(Matcher<T>... matchers) {
56+
return new IsCollectionOnlyContaining<T>(anyOf(matchers));
57+
}
58+
}

0 commit comments

Comments
 (0)