Shaun Abram
Technology and Leadership Blog
Hamcrest Matcher
As a follow up to the Hamcrest post I made yesterday, I wanted to post an example of my own Hamcrest matcher implementation. This matcher tests if a string contains a specified number of substrings.
An example usage could be:
String sql = "select a,b,c from tableA";
assertThat(sql, hasNumberOfSubstrings(",", 2));
See the source code below. I have been reading up on OSS licenses recently and decided to release this using the same license as Hamcrest – the new BSD license.
I have also attached a jar which includes the associated unit tests, although you will need the hamcrest-unit-test project to compile, which can be downloaded as part of the hamcrest all-in-one jar.
package com.shaunabram.hamcrest;
import java.util.regex.Pattern;
import org.hamcrest.*;
/**
* Matcher which tests if a string contains a specified number of substrings.
*
* @author sabram
*/
public class HasNumberOfSubstrings extends TypeSafeMatcher {
private final String substring;
private final int count;
public HasNumberOfSubstrings(String substring, int count) {
this.substring = substring;
this.count = count;
}
@Override
protected boolean matchesSafely(String item) {
Pattern p = Pattern.compile(substring);
java.util.regex.Matcher m = p.matcher(item);
int actualCount = 0;
while (m.find()) {
actualCount++;
}
if (actualCount == count) return true;
else return false;
}
public void describeTo(Description description) {
description.appendText("String containing ")
.appendText(count + " occurences of ")
.appendText(substring);
}
@Override
public void describeMismatchSafely(String item, Description mismatchDescription) {
mismatchDescription.appendValue(count)
.appendText(" occurence(s) of ")
.appendValue(substring)
.appendText(" in ")
.appendText(item);
}
@Factory
public static Matcher hasNumberOfSubstrings(String substring, int count) {
return new HasNumberOfSubstrings(substring, count);
}
}
Tags: Hamcrest, JUnit, Testing, unittesting