I have a matcher that checks a list over a range for a certain value
[code]
package hamcrest;
import java.util.List;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.junit.matchers.TypeSafeMatcher;
public class HasValueInRange extends TypeSafeMatcher<List<? extends
Object>> {
private final Object value;
private final int from;
private final int to;
private HasValueInRange(Object value, int from, int to) {
this.value = value;
this.from = from;
this.to = to;
}
public void describeTo(Description description) {
// TODO Auto-generated method stub
}
@Override
public boolean matchesSafely(List<? extends Object> values) {
// Verify range is valid and in array
if (from > to || to > values.size()) {
return false;
}
for (int i = from; i < to; i++) {
// If I am not equal I am done return false
if (!values.get(i).equals(value)) {
return false;
}
}
return true;
}
@Factory
public static HasValueInRange hasValueInRange(Object value, int from,
int to) {
return new HasValueInRange(value, from, to);
}
}
[/code]
I am using it as follows:
[code]
List<String> test= Arrays.asList(new String[]
{"Hello","Hello","Hello","Goodbye"});
assertThat(test, hasValueInRange("Hello", 0, 2); // This will pass
assertThat(test, hasValueInRange("Hello", 0, 3); // fail last element
is "Goodbye"
[/code]
This works great, however I would really like to be more expressive
and write the assert using nested Matchers, i.e.
[code]
List<String> test= Arrays.asList(new String[]
{"Hello","Hello","Hello","Goodbye"});
assertThat(test, hasValue("Hello", inRange(0, 2)); // This will pass
assertThat(test, hasValue("Hello", inRange(0, 3)); // fail last
element is "Goodbye"
[/code]
So I want to pass an inRange matcher to the hasValue matcher. I am
really struggling on how do implement this. I am just playing with
hamcrest and trying to learn, thanks for any help!