Skip to content

Instantly share code, notes, and snippets.

@adamv
Created March 25, 2016 19:39
Show Gist options
  • Save adamv/4db409f45e36871bda5b to your computer and use it in GitHub Desktop.
Save adamv/4db409f45e36871bda5b to your computer and use it in GitHub Desktop.
package test.util;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
import java.io.IOException;
import java.net.URL;
/**
* A Matcher that tests that the JSON given as a string is equivalent to
* the JSON from a string read from a resource.
*/
class JsonResourceMatcher extends TypeSafeMatcher<String> {
private static final ObjectMapper MAPPER = new ObjectMapper();
private final JsonNode expected;
JsonResourceMatcher(final String resourceName) throws IOException {
final ClassLoader loader = Thread.currentThread().getContextClassLoader();
final URL resource = loader.getResource(resourceName);
if (resource == null) {
throw new IllegalArgumentException("Resource " + resourceName + " was not found.");
}
this.expected = MAPPER.readTree(resource);
}
@Override
protected boolean matchesSafely(final String item) {
final JsonNode actual;
try {
actual = MAPPER.readTree(item);
} catch (final IOException ignored) {
// TODO - describe failure - response body wasn't valid JSON
return false;
}
return expected.equals(actual);
}
@Override
public void describeTo(final Description description) {
description.appendText(expected.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment