Skip to content

Instantly share code, notes, and snippets.

@mroger
Last active June 2, 2016 00:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mroger/4937200129184e04389d42d3624fc8ac to your computer and use it in GitHub Desktop.
Save mroger/4937200129184e04389d42d3624fc8ac to your computer and use it in GitHub Desktop.
Hamcrest custom matcher using dynamic proxy
public class MagicMatcher <T> implements InvocationHandler {
//...
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if ("matches".equals(method.getName())) {
for (Entry<String, Object> entry : methodMap.entrySet()) {
String field = entry.getKey().substring(entry.getKey().indexOf("with") + 4);
Object objectValue = extractObjectValue((T) args[0], entry.getKey());
if (!(entry.getValue() instanceof Matcher)) {
resultDescription.addExpectedDescription(field, objectValue);
if (!entry.getValue().equals(objectValue)) {
resultDescription.addMismatchDescription(field, entry.getValue());
return new Boolean(false);
}
} else {
Matcher<?> matcher = (Matcher<?>) entry.getValue();
resultDescription.addExpectedDescription(field, objectValue);
if (!matcher.matches(objectValue)) {
resultDescription.addMismatchDescription(field, objectValue);
return new Boolean(false);
}
}
}
return new Boolean(true);
} else if ("describeTo".equals(method.getName())) {
Description description = (Description) args[0];
description.appendText(resultDescription.getExpectedDescription());
return null;
} else if ("describeMismatch".equals(method.getName())) {
Description description = (Description) args[1];
description.appendText(resultDescription.getMismatchDescription());
return null;
} else {
if (args.length > 1) {
throw new IllegalArgumentException("Cannot assert more than one argument at once.");
}
methodMap.put(method.getName(), args[0]);
return proxy;
}
}
//...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment