Skip to content

Commit 0fc0130

Browse files
author
nat.pryce
committed
added StringContainsInOrder matcher
1 parent 7fabb5c commit 0fc0130

2 files changed

Lines changed: 61 additions & 0 deletions

File tree

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package org.hamcrest.text;
2+
3+
import org.hamcrest.Description;
4+
import org.hamcrest.TypeSafeMatcher;
5+
6+
public class StringContainsInOrder extends TypeSafeMatcher<String> {
7+
private final Iterable<String> substrings;
8+
9+
public StringContainsInOrder(Iterable<String> substrings) {
10+
this.substrings = substrings;
11+
}
12+
13+
@Override
14+
public boolean matchesSafely(String s) {
15+
int fromIndex = 0;
16+
17+
for (String substring : substrings) {
18+
fromIndex = s.indexOf(substring, fromIndex);
19+
if (fromIndex == -1) {
20+
return false;
21+
}
22+
}
23+
24+
return true;
25+
}
26+
27+
public void describeTo(Description description) {
28+
description.appendText("a string containing ")
29+
.appendValueList("", ", ", "", substrings)
30+
.appendText(" in order");
31+
}
32+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package org.hamcrest.text;
2+
3+
import static java.util.Arrays.asList;
4+
5+
import org.hamcrest.AbstractMatcherTest;
6+
import org.hamcrest.Matcher;
7+
8+
9+
public class StringContainsInOrderTest extends AbstractMatcherTest {
10+
StringContainsInOrder m = new StringContainsInOrder(asList("a", "b", "c"));
11+
12+
public void testMatchesOnlyIfStringContainsGivenSubstringsInTheSameOrder() {
13+
assertMatches("substrings in order", m, "abc");
14+
assertMatches("substrings separated", m, "1a2b3c4");
15+
16+
assertDoesNotMatch("substrings out of order", m, "cab");
17+
assertDoesNotMatch("no substrings in string", m, "xyz");
18+
assertDoesNotMatch("substring missing", m, "ac");
19+
assertDoesNotMatch("empty string", m, "");
20+
}
21+
22+
public void testDescribesItselfHelpfully() {
23+
assertDescription("a string containing \"a\", \"b\", \"c\" in order", m);
24+
}
25+
26+
protected Matcher<?> createMatcher() {
27+
return m;
28+
}
29+
}

0 commit comments

Comments
 (0)