自定义Hamcrest匹配器
2018-04-14 本文已影响3人
changer0
本篇将通过多种方式自定义Hamcrest匹配器.
通过FeatureMatcher自定义Hamcrest匹配器
创建Hamcrest匹配器
我们自定义一个为String提供长度的匹配器,需要利用FeatureMatcher类,封装一个现有的匹配器,用来决定给定的被测对象的哪个字段匹配,并且提供丰富的错误信息.FeatureMatcher的构造函数有下列参数:
- 我们想要包装的匹配器
- 对我们测试的功能的描述(在错误信息会有体现)
- 测试功能的名字(在错误信息会有体现)
我们必须重写featureValueOf(T actual),它的返回值将传入matchesSafely()方法进行匹配判断.
public static Matcher<String> length(Matcher<? super Integer> matcher) {
return new FeatureMatcher<String, Integer>(matcher,
"a String of length that", "length") {
@Override
protected Integer featureValueOf(String actual) {
return actual.length();
}
};
}
测试验证
使用你刚才创建的自定义匹配器验证"Gandalf"的长度为8
@Test
public void fellowShipOfTheRingShouldContainer7() {
assertThat("Gandalf", length(is(8)));
}
通过控制台错误信息我们能明确的看到"Gandalf"的实际长度与预期不符.

使用TypeSafeMatcher自定义匹配器
我们可以对TypeSafeMatcher进行扩展.与BaseMatcher相比TypeSafeMatcher可以自动的检查null值, 在被委派到matchesSafely()方法之前检查类型并进行适当的转换.下面定义了一个检查一个字符串是否匹配正则关系的匹配器.
public class RegexMatcher extends TypeSafeMatcher<String> {
private final String regex;
public RegexMatcher(final String regex) {
this.regex = regex;
}
@Override
public void describeTo(final Description description) {
description.appendText("matches regular expression=`" + regex + "`");
}
@Override
public boolean matchesSafely(final String string) {
return string.matches(regex);
}
// matcher method you can call on this matcher class
public static RegexMatcher matchesRegex(final String regex) {
return new RegexMatcher(regex);
}
}
通过下面的代码进行测试.
@Test
public void testRegularExpressionMatcher() throws Exception {
String s ="aaabbbaaaa";
assertThat(s, RegexMatcher.matchesRegex("a*b*a*"));
}
自定义组合匹配器
为什么要自定义组合匹配器
Hamcrest有内置的组合匹配器,但是它的可读性太差!
下面就是一个案例:
@Test
public void testCombining() {
List<Integer> list = new ArrayList<>();
assertThat(list, both(hasSize(1)).and(contains(42)));
}
执行结果:

可读性差,无法准确描述错误信息.
创建自定义组合匹配器
我们可以继承BaseMatchers类使用它提供对外连接的方法(matches),本身再提供一个添加方法(add).将匹配器链接起来.并保存在集合中.
public class MatcherCombinator<T> extends BaseMatcher<T> {
private final List<Matcher<? super T>> matchers = new ArrayList<>();
private final List<Matcher<? super T>> failedMatchers = new ArrayList<>();
private MatcherCombinator(final Matcher<? super T> matcher) {
matchers.add(matcher);
}
public MatcherCombinator<T> and(final Matcher<? super T> matcher) {
matchers.add(matcher);
return this;
}
@Override
public boolean matches(final Object item) {
boolean matchesAllMatchers = true;
for (final Matcher<? super T> matcher : matchers) {
if (!matcher.matches(item)) {
failedMatchers.add(matcher);
matchesAllMatchers = false;
}
}
return matchesAllMatchers;
}
@Override
public void describeTo(final Description description) {
description.appendValueList("\n", " " + "and" + "\n", "", matchers);
}
@Override
public void describeMismatch(final Object item, final Description description) {
description.appendText("\n");
for (Iterator<Matcher<? super T>> iterator = failedMatchers.iterator(); iterator.hasNext();) {
final Matcher<? super T> matcher = iterator.next();
description.appendText("Expected: <");
description.appendDescriptionOf(matcher).appendText(" but ");
matcher.describeMismatch(item, description);
if (iterator.hasNext()) {
description.appendText(">\n");
}
}
}
public static <LHS> MatcherCombinator<LHS> matches(final Matcher<? super LHS> matcher) {
return new MatcherCombinator<LHS>(matcher);
}
}
组合匹配器的使用和执行结果:
@Test
public void testCustomCombining() {
List<Integer> list = new ArrayList<>();
assertThat(list, MatcherCombinator.matches(hasSize(1)).and(contains(42)));
}

可读性大大提高.可以准确的定位到问题.
